Hugging Face Chat
Hugging Face Text Generation Inference (TGI) 是一種專門用於在雲端部署大型語言模型 (LLM) 的解決方案,使其可以透過 API 訪問。TGI 透過連續批處理、令牌流和高效記憶體管理等功能為文字生成任務提供最佳化的效能。
Text Generation Inference 要求模型與其架構特定的最佳化相容。雖然許多流行的 LLM 都受支援,但並非 Hugging Face Hub 上的所有模型都可以使用 TGI 部署。如果需要部署其他型別的模型,請考慮使用標準的 Hugging Face 推理終端。 |
有關受支援模型和架構的完整最新列表,請參閱 Text Generation Inference 受支援模型文件。 |
前提條件
您需要在 Hugging Face 上建立推理終端並建立 API 令牌來訪問該終端。更多詳情可在 此處 找到。Spring AI 專案定義了一個名為 spring.ai.huggingface.chat.api-key
的配置屬性,您應將其設定為從 Hugging Face 獲取的 API 令牌值。還有一個名為 spring.ai.huggingface.chat.url
的配置屬性,您應將其設定為在 Hugging Face 中預置模型時獲取的推理終端 URL。您可以在推理終端的 UI 上找到它,地址在 此處。匯出環境變數是設定這些配置屬性的一種方法。
export SPRING_AI_HUGGINGFACE_CHAT_API_KEY=<INSERT KEY HERE>
export SPRING_AI_HUGGINGFACE_CHAT_URL=<INSERT INFERENCE ENDPOINT URL HERE>
自動配置
Spring AI 自動配置、starter 模組的 artifact 名稱發生了重大變化。請參閱 升級說明 獲取更多資訊。 |
Spring AI 為 Hugging Face Chat Client 提供了 Spring Boot 自動配置。要啟用它,請將以下依賴項新增到您專案的 Maven pom.xml
檔案中
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-starter-model-huggingface</artifactId>
</dependency>
或新增到您的 Gradle build.gradle
構建檔案。
dependencies {
implementation 'org.springframework.ai:spring-ai-starter-model-huggingface'
}
請參閱 依賴管理 部分,將 Spring AI BOM 新增到您的構建檔案。 |
聊天屬性
現在透過帶有字首 要啟用, 要停用, 進行此更改是為了支援配置多個模型。 |
字首 spring.ai.huggingface
是用於配置 Hugging Face 聊天模型實現的屬性字首。
屬性 |
描述 |
預設值 |
|
用於向推理終端進行身份驗證的 API Key。 |
- |
|
要連線的推理終端 URL |
- |
|
啟用 Hugging Face 聊天模型。 |
true |
|
啟用 Hugging Face 聊天模型。 |
|
示例控制器(自動配置)
建立 一個新的 Spring Boot 專案,並將 spring-ai-starter-model-huggingface
新增到您的 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
介面,並使用[低層 API] 連線到 Hugging Face 推理終端。
將 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());