Hugging Face Chat
Hugging Face Text Generation Inference (TGI) 是一種專門的部署解決方案,用於在雲端中服務大型語言模型 (LLM),使其可透過 API 存取。TGI 透過持續批次處理、Token 串流和高效的記憶體管理等功能,為文字生成任務提供最佳化效能。
Text Generation Inference 要求模型與其架構特定的最佳化相容。雖然許多流行的 LLM 受到支援,但並非 Hugging Face Hub 上的所有模型都可以使用 TGI 部署。如果您需要部署其他類型的模型,請考慮改用標準的 Hugging Face Inference Endpoints。 |
如需受支援模型和架構的完整且最新的清單,請參閱Text Generation Inference 支援模型文件。 |
先決條件
您需要於 Hugging Face 上建立 Inference Endpoint,並建立 API Token 以存取該端點。更多詳細資訊請參閱此處。Spring AI 專案定義了一個名為 spring.ai.huggingface.chat.api-key
的組態屬性,您應將其設定為從 Hugging Face 取得的 API Token 值。還有一個名為 spring.ai.huggingface.chat.url
的組態屬性,您應將其設定為在 Hugging Face 中佈建模型時取得的 Inference Endpoint URL。您可以在 Inference Endpoint 的 UI 此處找到它。匯出環境變數是設定這些組態屬性的一種方式
export SPRING_AI_HUGGINGFACE_CHAT_API_KEY=<INSERT KEY HERE>
export SPRING_AI_HUGGINGFACE_CHAT_URL=<INSERT INFERENCE ENDPOINT URL HERE>
自動組態
Spring AI 為 Hugging Face Chat Client 提供 Spring Boot 自動組態。若要啟用它,請將以下相依性新增至您專案的 Maven pom.xml
檔案
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-huggingface-spring-boot-starter</artifactId>
</dependency>
或新增至您的 Gradle build.gradle
建置檔案。
dependencies {
implementation 'org.springframework.ai:spring-ai-huggingface-spring-boot-starter'
}
請參閱相依性管理章節,將 Spring AI BOM 新增至您的建置檔案。 |
範例控制器(自動組態)
建立新的 Spring Boot 專案,並將 spring-ai-huggingface-spring-boot-starter
新增至您的 pom(或 gradle)相依性中。
在 src/main/resources
目錄下新增 application.properties
檔案,以啟用和設定 Hugging Face 聊天模型
spring.ai.huggingface.chat.api-key=YOUR_API_KEY
spring.ai.huggingface.chat.url=YOUR_INFERENCE_ENDPOINT_URL
將 api-key 和 url 替換為您的 Hugging Face 值。 |
這將建立一個 HuggingfaceChatModel
實作,您可以將其注入到您的類別中。以下是一個簡單的 @Controller
類別範例,該類別使用聊天模型進行文字生成。
@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));
}
}
手動組態
HuggingfaceChatModel 實作了 ChatModel
介面,並使用 [low-level-api] 連接到 Hugging Face Inference Endpoint。
將 spring-ai-huggingface
相依性新增至您專案的 Maven pom.xml
檔案
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-huggingface</artifactId>
</dependency>
或新增至您的 Gradle build.gradle
建置檔案。
dependencies {
implementation 'org.springframework.ai:spring-ai-huggingface'
}
請參閱相依性管理章節,將 Spring AI BOM 新增至您的建置檔案。 |
接下來,建立一個 HuggingfaceChatModel
並將其用於文字生成
HuggingfaceChatModel chatModel = new HuggingfaceChatModel(apiKey, url);
ChatResponse response = this.chatModel.call(
new Prompt("Generate the names of 5 famous pirates."));
System.out.println(response.getGeneration().getResult().getOutput().getContent());