HuggingFace聊天

HuggingFace推理终端让您在云中部署和提供机器学习模型,通过API可访问它们。

入门

有关HuggingFace推理终端的更多详细信息可以在此处找到。

前提条件

添加spring-ai-huggingface依赖项:

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

您应该获取自己的HuggingFace API密钥并将其设置为环境变量

export HUGGINGFACE_API_KEY=your_api_key_here
有关如何将Spring AI BOM添加到构建文件的信息,请参阅依赖关系管理部分。

请注意,此客户端实现尚未有Spring Boot Starter。

获取推理终端的终端点URL。您可以在此处找到此终端点的UIhere

调用模型

HuggingfaceChatClient client = new HuggingfaceChatClient(apiKey, basePath);
Prompt prompt = new Prompt("Your text here...");
ChatResponse response = client.call(prompt);
System.out.println(response.getGeneration().getText());

示例

使用此处找到的示例

String mistral7bInstruct = """
        [INST] You are a helpful code assistant. Your task is to generate a valid JSON object based on the given information:
        name: John
        lastname: Smith
        address: #1 Samuel St.
        Just generate the JSON object without explanations:
        [/INST]""";
Prompt prompt = new Prompt(mistral7bInstruct);
ChatResponse aiResponse = huggingfaceChatClient.call(prompt);
System.out.println(response.getGeneration().getText());

将产生输出

{
    "name": "John",
    "lastname": "Smith",
    "address": "#1 Samuel St."
}