收藏本站,收获最前沿的人工智能与编程资讯!!

Spring AI 使用 Hugging Face 对话模型

技术文档 13℃ 0

Hugging Face 文本生成推理引擎(TGI)是一款专门用于在云端部署大语言模型(LLM)的服务化解决方案,可通过 API 对外提供模型服务。TGI 通过持续批处理、令牌流式传输、高效内存管理等特性,为文本生成任务提供了极致的性能优化。

文本生成推理引擎要求模型与其架构专属优化方案兼容。虽然支持许多主流大语言模型,但并非 Hugging Face Hub 上的所有模型都能使用 TGI 部署。如果你需要部署其他类型的模型,建议使用标准的 Hugging Face 推理端点。    
如需查看完整且最新的支持模型与架构列表,参考文本生成推理引擎支持模型文档。

前提条件

你需要在 Hugging Face 上创建推理端点,并生成 API 令牌用于访问该端点。

Spring AI 提供两个核心配置项:

  • spring.ai.huggingface.chat.api-key:设置为从 Hugging Face 获取的 API 令牌

  • spring.ai.huggingface.chat.url:设置为在 Hugging Face 部署模型时分配的推理端点 URL

基础配置(application.properties)

spring.ai.huggingface.chat.api-key=<your-huggingface-api-key>
spring.ai.huggingface.chat.url=<your-inference-endpoint-url>

安全配置(环境变量)

# application.yml
spring:
  ai:
    huggingface:
      chat:
        api-key: ${HUGGINGFACE_API_KEY}
        url: ${HUGGINGFACE_ENDPOINT_URL}

# 环境变量配置
export HUGGINGFACE_API_KEY=<your-huggingface-api-key>
export HUGGINGFACE_ENDPOINT_URL=<your-inference-endpoint-url>

添加仓库与依赖管理

Spring AI 构件已发布至 Maven 中央仓库。建议使用 BOM 统一管理项目版本,保证依赖一致性。

自动配置

Spring AI 为 Hugging Face 对话客户端提供开箱即用的自动配置,添加以下依赖即可启用:

<dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-starter-model-huggingface</artifactId>
</dependency>

对话属性配置

现在通过顶级属性 spring.ai.model.chat 启用/禁用对话自动配置:

  • 启用:spring.ai.model.chat=huggingface(默认启用)

  • 禁用:spring.ai.model.chat=none

spring.ai.huggingface 前缀用于配置 Hugging Face 对话模型:

属性描述默认值
spring.ai.huggingface.chat.api-key用于认证推理端点的 API 密钥-
spring.ai.huggingface.chat.url要连接的推理端点地址-
spring.ai.model.chat启用 Hugging Face 对话模型huggingface

示例控制器(自动配置)

创建 Spring Boot 项目,添加依赖并完成配置后,即可注入 HuggingfaceChatModel 使用:

@RestController
public class ChatController {

    private final HuggingfaceChatModel chatModel;

    @Autowired
    public ChatController(HuggingfaceChatModel chatModel) {
        this.chatModel = chatModel;
    }

    @GetMapping("/ai/generate")
    public Map generate(@RequestParam(value = "message", defaultValue = "Tell me a joke") String message) {
        return Map.of("generation", this.chatModel.call(message));
    }
}

手动配置

步骤1:添加核心依赖

<dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-huggingface</artifactId>
</dependency>

步骤2:手动创建模型实例

// 从环境变量/配置中心获取凭证
String apiKey = System.getenv("HUGGINGFACE_API_KEY");
String endpointUrl = System.getenv("HUGGINGFACE_ENDPOINT_URL");

// 初始化对话模型
HuggingfaceChatModel chatModel = new HuggingfaceChatModel(apiKey, endpointUrl);

// 调用模型生成文本
ChatResponse response = chatModel.call(
    new Prompt("Generate the names of 5 famous pirates."));

// 输出结果
System.out.println(response.getResult().getOutput().getText());

相关推荐