Huggingface.js documentation

🤗 Hugging Face 推理

Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

🤗 Hugging Face 推理

一个由 Typescript 驱动的封装器,为在 Hugging Face Hub 上托管的模型提供跨多个服务运行推理的统一接口:

  1. 推理服务提供商:通过我们的无服务器推理合作伙伴,提供对数百个机器学习模型的简化、统一访问。这种新方法基于我们之前的 Serverless Inference API,得益于世界级的服务提供商,提供了更多的模型、更好的性能和更高的可靠性。有关支持的服务提供商列表,请参阅文档。
  2. Inference Endpoints:一款可轻松将模型部署到生产环境的产品。推理由 Hugging Face 在您选择的云服务商上,通过专用的全托管基础设施运行。
  3. 本地端点:你还可以通过将客户端连接到这些本地端点,使用 llama.cpp、Ollama、vLLM、LiteLLM 或 Text Generation Inference (TGI) 等本地推理服务器来运行推理。

入门

安装

节点

npm install @huggingface/inference

pnpm add @huggingface/inference

yarn add @huggingface/inference

Deno

// esm.sh
import { InferenceClient } from "https://esm.sh/@huggingface/inference";
// or npm:
import { InferenceClient } from "npm:@huggingface/inference";

初始化

import { InferenceClient } from '@huggingface/inference';

const hf = new InferenceClient('your access token');

❗重要提示:请务必传入访问令牌。加入 Hugging Face 后,访问 访问令牌 页面即可免费生成您的访问令牌。

您的访问令牌应妥善保管。如果需要在前端应用中对其进行保护,我们建议设置一个代理服务器来存储访问令牌。

使用推理提供商

您可以使用推理客户端向第三方提供商发送推理请求。

目前,我们支持以下提供商:

要向第三方提供商发送请求,您必须将 provider 参数传递给推理函数。provider 参数的默认值为 “auto”,它将根据您在 https://hf.co/settings/inference-providers 中设置的偏好顺序,选择该模型可用的第一个提供商。

const accessToken = "hf_..."; // Either a HF access token, or an API key from the third-party provider (Replicate in this example)

const client = new InferenceClient(accessToken);
await client.textToImage({
  provider: "replicate",
  model:"black-forest-labs/Flux.1-dev",
  inputs: "A black forest cake"
})

您还必须确保您的请求已通过访问令牌进行身份验证。 当使用 Hugging Face 访问令牌进行身份验证时,请求将通过 https://huggingface.co. 路由。当使用第三方提供商密钥进行身份验证时,请求将直接针对该提供商的推理 API 发出。

在请求第三方提供商时,仅支持部分模型。您可以在此处查看各流水线任务支持的模型列表:

❗重要说明:为了保持兼容性,第三方 API 必须遵循我们在 HF 模型页面上针对每种流水线任务类型所预期的“标准”形状 API。 对于 LLM 而言,由于大家最终都统一采用了 OpenAI API,因此这不是一个问题;但对于“text-to-image”或“automatic-speech-recognition”等其他任务,由于不存在标准 API,情况可能会更复杂。如果需要帮助,或者我们可以帮助您简化流程,请告诉我们!

👋想要添加其他提供商?如果您希望添加对其他推理提供商的支持,请随时联系我们,并/或在 https://huggingface.co/spaces/huggingface/HuggingDiscussions/discussions/49 上提出请求

Tree-shaking

您可以直接从模块中导入所需的函数,而无需使用 InferenceClient 类。

import { textGeneration } from "@huggingface/inference";

await textGeneration({
  accessToken: "hf_...",
  model: "model_or_endpoint",
  inputs: ...,
  parameters: ...
})

这将使您的打包工具能够执行 tree-shaking。

错误处理

推理包提供了特定的错误类型,帮助您有效处理不同的错误场景。

错误类型

该包定义了几种扩展自基础 Error 类的错误类型:

  • InferenceClientError:所有 Hugging Face Inference 错误的基础错误类
  • InferenceClientInputError:当输入参数存在问题时抛出
  • InferenceClientProviderApiError:当提供商出现 API 级别的错误时抛出
  • InferenceClientHubApiError:当 Hugging Face Hub 出现 API 级别的错误时抛出
  • InferenceClientProviderOutputError:当提供商的 API 响应格式存在问题时抛出

使用示例

import { InferenceClient } from "@huggingface/inference";
import {
  InferenceClientError,
  InferenceClientInputError,
  InferenceClientProviderApiError,
  InferenceClientProviderOutputError,
  InferenceClientHubApiError,
} from "@huggingface/inference";

const client = new InferenceClient();

try {
  const result = await client.textGeneration({
    model: "gpt2",
    inputs: "Hello, I'm a language model",
  });
} catch (error) {
  if (error instanceof InferenceClientProviderApiError) {
    // Handle API errors (e.g., rate limits, authentication issues)
    console.error("Provider API Error:", error.message);
    console.error("HTTP Request details:", error.httpRequest);
    console.error("HTTP Response details:", error.httpResponse);
  } else if (error instanceof InferenceClientHubApiError) {
    // Handle API errors (e.g., rate limits, authentication issues)
    console.error("Hub API Error:", error.message);
    console.error("HTTP Request details:", error.httpRequest);
    console.error("HTTP Response details:", error.httpResponse);
  } else if (error instanceof InferenceClientProviderOutputError) {
    // Handle malformed responses from providers
    console.error("Provider Output Error:", error.message);
  } else if (error instanceof InferenceClientInputError) {
    // Handle invalid input parameters
    console.error("Input Error:", error.message);
  } else {
    // Handle unexpected errors
    console.error("Unexpected error:", error);
  }
}

/// Catch all errors from @huggingface/inference
try {
  const result = await client.textGeneration({
    model: "gpt2",
    inputs: "Hello, I'm a language model",
  });
} catch (error) {
  if (error instanceof InferenceClientError) {
    // Handle errors from @huggingface/inference
    console.error("Error from InferenceClient:", error);
  } else {
    // Handle unexpected errors
    console.error("Unexpected error:", error);
  }
}

错误详情

InferenceClientProviderApiError

当在所选提供商处执行推理时,如果 API 请求存在问题,则会出现此错误。

它具有以下属性:

  • message:描述性错误信息
  • httpRequest:有关失败请求的详细信息(URL、方法、请求头)
  • httpResponse:响应详情,包括状态码和响应体

InferenceClientHubApiError

当请求 Hugging Face Hub API 时,如果 API 请求存在问题,就会发生此错误。

它具有以下属性:

  • message:描述性错误信息
  • httpRequest:有关失败请求的详细信息(URL、方法、请求头)
  • httpResponse:响应详情,包括状态码和响应体

InferenceClientProviderOutputError

当提供商返回的响应格式不符合预期时,会出现此错误。

InferenceClientInputError

当输入参数无效或缺失时,会出现此错误。错误信息会说明输入存在什么问题。

自然语言处理

文本生成

根据输入提示生成文本。

await hf.textGeneration({
  model: 'mistralai/Mixtral-8x7B-v0.1',
  provider: "together",
  inputs: 'The answer to the universe is'
})

for await (const output of hf.textGenerationStream({
  model: "mistralai/Mixtral-8x7B-v0.1",
  provider: "together",
  inputs: 'repeat "one two three four"',
  parameters: { max_new_tokens: 250 }
})) {
  console.log(output.token.text, output.generated_text);
}

聊天补全

根据包含对话的消息列表生成模型响应。

// Non-streaming API
const out = await hf.chatCompletion({
  model: "Qwen/Qwen3-32B",
  provider: "cerebras",
  messages: [{ role: "user", content: "Hello, nice to meet you!" }],
  max_tokens: 512,
  temperature: 0.1,
});

// Streaming API
let out = "";
for await (const chunk of hf.chatCompletionStream({
  model: "Qwen/Qwen3-32B",
  provider: "cerebras",
  messages: [
    { role: "user", content: "Can you help me solve an equation?" },
  ],
  max_tokens: 512,
  temperature: 0.1,
})) {
  if (chunk.choices && chunk.choices.length > 0) {
    out += chunk.choices[0].delta.content;
  }
}

特征提取

此任务读取一些文本并输出原始浮点值,这些值通常作为语义数据库/语义搜索的一部分被使用。

await hf.featureExtraction({
  model: "sentence-transformers/distilbert-base-nli-mean-tokens",
  inputs: "That is a happy person",
});

填充掩码

尝试用缺失的单词(更准确地说是 token)来填补一个空缺。

await hf.fillMask({
  model: 'bert-base-uncased',
  inputs: '[MASK] world!'
})

摘要

将较长的文本总结为较短的文本。请注意,某些模型对输入长度有最大限制。

await hf.summarization({
  model: 'facebook/bart-large-cnn',
  inputs:
    'The tower is 324 metres (1,063 ft) tall, about the same height as an 81-storey building, and the tallest structure in Paris. Its base is square, measuring 125 metres (410 ft) on each side. During its construction, the Eiffel Tower surpassed the Washington Monument to become the tallest man-made structure in the world, a title it held for 41 years until the Chrysler Building in New York City was finished in 1930.',
  parameters: {
    max_length: 100
  }
})

问答

根据您提供的上下文回答问题。

await hf.questionAnswering({
  model: 'deepset/roberta-base-squad2',
  inputs: {
    question: 'What is the capital of France?',
    context: 'The capital of France is Paris.'
  }
})

表格问答

await hf.tableQuestionAnswering({
  model: 'google/tapas-base-finetuned-wtq',
  inputs: {
    query: 'How many stars does the transformers repository have?',
    table: {
      Repository: ['Transformers', 'Datasets', 'Tokenizers'],
      Stars: ['36542', '4512', '3934'],
      Contributors: ['651', '77', '34'],
      'Programming language': ['Python', 'Python', 'Rust, Python and NodeJS']
    }
  }
})

文本分类

该方法常用于情感分析,会为给定文本分配标签,并给出该标签的概率得分。

await hf.textClassification({
  model: 'distilbert-base-uncased-finetuned-sst-2-english',
  inputs: 'I like you. I love you.'
})

Token 分类

用于句子解析,包括语法分析或命名实体识别(NER),以理解文本中包含的关键词。

await hf.tokenClassification({
  model: 'dbmdz/bert-large-cased-finetuned-conll03-english',
  inputs: 'My name is Sarah Jessica Parker but you can call me Jessica'
})

翻译

将文本从一种语言转换为另一种语言。

await hf.translation({
  model: 't5-base',
  inputs: 'My name is Wolfgang and I live in Berlin'
})

await hf.translation({
  model: 'facebook/mbart-large-50-many-to-many-mmt',
  inputs: textToTranslate,
  parameters: {
  "src_lang": "en_XX",
  "tgt_lang": "fr_XX"
 }
})

零样本分类

检查输入文本与所提供的一组标签的匹配程度。

await hf.zeroShotClassification({
  model: 'facebook/bart-large-mnli',
  inputs: [
    'Hi, I recently bought a device from your company but it is not working as advertised and I would like to get reimbursed!'
  ],
  parameters: { candidate_labels: ['refund', 'legal', 'faq'] }
})

句子相似度

计算一段文本与一组其他句子之间的语义相似度。

await hf.sentenceSimilarity({
  model: 'sentence-transformers/paraphrase-xlm-r-multilingual-v1',
  inputs: {
    source_sentence: 'That is a happy person',
    sentences: [
      'That is a happy dog',
      'That is a very happy person',
      'Today is a sunny day'
    ]
  }
})

文本排序

根据查询的相关性对文档进行排序。

await hf.textRanking({
  model: 'cross-encoder/ettin-reranker-68m-v1',
  inputs: {
    query: 'Which planet is known as the Red Planet?',
    texts: [
      "Venus is often called Earth's twin because of its similar size and proximity.",
      'Mars, known for its reddish appearance, is often referred to as the Red Planet.',
      'Jupiter, the largest planet in our solar system, has a prominent red spot.',
      'Saturn, famous for its rings, is sometimes mistaken for the Red Planet.'
    ]
  }
})

音频

自动语音识别

从音频文件中转录语音。

演示

await hf.automaticSpeechRecognition({
  model: 'facebook/wav2vec2-large-960h-lv60-self',
  data: readFileSync('test/sample1.flac')
})

音频分类

为给定的音频分配标签,并给出该标签的概率分数。

演示

await hf.audioClassification({
  model: 'superb/hubert-large-superb-er',
  data: readFileSync('test/sample1.flac')
})

文本转语音

根据文本输入生成自然流畅的语音。

交互式教程

await hf.textToSpeech({
  model: 'espnet/kan-bayashi_ljspeech_vits',
  inputs: 'Hello world!'
})

音频到音频

根据输入音频生成一个或多个音频,常用于语音增强和声源分离。

await hf.audioToAudio({
  model: 'speechbrain/sepformer-wham',
  data: readFileSync('test/sample1.flac')
})

计算机视觉

图像分类

为给定图像分配标签,并给出该标签的概率分数。

演示

await hf.imageClassification({
  data: readFileSync('test/cheetah.png'),
  model: 'google/vit-base-patch16-224'
})

目标检测

检测图像中的对象,并返回对应的标签、边界框和概率分数。

演示

await hf.objectDetection({
  data: readFileSync('test/cats.png'),
  model: 'facebook/detr-resnet-50'
})

图像分割

检测图像中的片段,并返回带有相应边界框和概率分数的标签。

await hf.imageSegmentation({
  data: readFileSync('test/cats.png'),
  model: 'facebook/detr-resnet-50-panoptic'
})

图像转文本

从给定图像中输出文本,通常用于图像描述或光学字符识别。

await hf.imageToText({
  data: readFileSync('test/cats.png'),
  model: 'nlpconnect/vit-gpt2-image-captioning'
})

文本到图像

根据文本提示创建图像。

演示

await hf.textToImage({
  model: 'black-forest-labs/FLUX.1-dev',
  inputs: 'a picture of a green bird'
})

图像到图像

图像到图像(Image-to-image)任务是将源图像转换为匹配目标图像或目标图像域的特征。

交互式教程

await hf.imageToImage({
  inputs: new Blob([readFileSync("test/stormtrooper_depth.png")]),
  parameters: {
    prompt: "elmo's lecture",
  },
  model: "lllyasviel/sd-controlnet-depth",
});

零样本图像分类

检查输入图像与您提供的一组标签的匹配程度。

await hf.zeroShotImageClassification({
  model: 'openai/clip-vit-large-patch14-336',
  inputs: {
    image: await (await fetch('https://placekitten.com/300/300')).blob()
  },
  parameters: {
    candidate_labels: ['cat', 'dog']
  }
})

多模态

视觉问答

视觉问答(Visual Question Answering)是指根据图像回答开放式问题的任务。它们针对自然语言问题输出自然语言回答。

演示

await hf.visualQuestionAnswering({
  model: 'dandelin/vilt-b32-finetuned-vqa',
  inputs: {
    question: 'How many cats are lying down?',
    image: await (await fetch('https://placekitten.com/300/300')).blob()
  }
})

文档问答

文档问答模型以(文档,问题)对作为输入,并以自然语言返回答案。

演示

await hf.documentQuestionAnswering({
  model: 'impira/layoutlm-document-qa',
  inputs: {
    question: 'Invoice number?',
    image: await (await fetch('https://huggingface.co/spaces/impira/docquery/resolve/2359223c1837a7587402bda0f2643382a6eefeab/invoice.png')).blob(),
  }
})

表格

表格回归

表格回归是在给定一组属性的情况下预测一个数值值的任务。

await hf.tabularRegression({
  model: "scikit-learn/Fish-Weight",
  inputs: {
    data: {
      "Height": ["11.52", "12.48", "12.3778"],
      "Length1": ["23.2", "24", "23.9"],
      "Length2": ["25.4", "26.3", "26.5"],
      "Length3": ["30", "31.2", "31.1"],
      "Species": ["Bream", "Bream", "Bream"],
      "Width": ["4.02", "4.3056", "4.6961"]
    },
  },
})

表格分类

表格分类任务是根据一组属性将目标类别(组)进行分类。

await hf.tabularClassification({
  model: "vvmnnnkv/wine-quality",
  inputs: {
    data: {
      "fixed_acidity": ["7.4", "7.8", "10.3"],
      "volatile_acidity": ["0.7", "0.88", "0.32"],
      "citric_acid": ["0", "0", "0.45"],
      "residual_sugar": ["1.9", "2.6", "6.4"],
      "chlorides": ["0.076", "0.098", "0.073"],
      "free_sulfur_dioxide": ["11", "25", "5"],
      "total_sulfur_dioxide": ["34", "67", "13"],
      "density": ["0.9978", "0.9968", "0.9976"],
      "pH": ["3.51", "3.2", "3.23"],
      "sulphates": ["0.56", "0.68", "0.82"],
      "alcohol": ["9.4", "9.8", "12.6"]
    },
  },
})

您可以使用任何兼容 Chat Completion API 的提供商来调用 chatCompletion 方法。

// Chat Completion Example
const MISTRAL_KEY = process.env.MISTRAL_KEY;
const hf = new InferenceClient(MISTRAL_KEY, {
  endpointUrl: "https://api.mistral.ai",
});
const stream = hf.chatCompletionStream({
  model: "mistral-tiny",
  messages: [{ role: "user", content: "Complete the equation one + one = , just the answer" }],
});
let out = "";
for await (const chunk of stream) {
  if (chunk.choices && chunk.choices.length > 0) {
    out += chunk.choices[0].delta.content;
    console.log(out);
  }
}

使用推理端点

上述示例使用的是推理提供商。虽然它们在快速原型设计和测试方面非常有用,但当你准备将模型部署到生产环境时,就需要使用专用的基础设施。这时Inference Endpoints就派上用场了。它允许你部署任意模型并将其暴露为私有 API。部署完成后,你将获得一个可以连接的 URL:

import { InferenceClient } from '@huggingface/inference';

const hf = new InferenceClient("hf_xxxxxxxxxxxxxx", {
	endpointUrl: "https://j3z5luu0ooo76jnl.us-east-1.aws.endpoints.huggingface.cloud/v1/",
});

const response = await hf.chatCompletion({
	messages: [
		{
			role: "user",
			content: "What is the capital of France?",
		},
	],
});

console.log(response.choices[0].message.content);

默认情况下,对推理端点的所有调用都会等待模型加载完成。当端点启用了缩容至 0时,这可能会导致较长的等待时间。如果您希望禁用此行为并自行处理端点返回的 500 HTTP 错误,可以按以下方式操作:

const hf = new InferenceClient("hf_xxxxxxxxxxxxxx", {
	endpointUrl: "https://j3z5luu0ooo76jnl.us-east-1.aws.endpoints.huggingface.cloud/v1/",
});

const response = await hf.chatCompletion(
	{
		messages: [
			{
				role: "user",
				content: "What is the capital of France?",
			},
		],
	},
	{
		retry_on_error: false,
	}
);

使用本地端点

您可以使用 InferenceClient 在本地推理服务器(llama.cpp、vllm、litellm server、TGI、mlx 等)上运行聊天补全,这些服务器运行在您自己的机器上。该 API 应与 OpenAI API 兼容。

import { InferenceClient } from '@huggingface/inference';

const hf = new InferenceClient(undefined, {
	endpointUrl: "http://localhost:8080",
});

const response = await hf.chatCompletion({
	messages: [
		{
			role: "user",
			content: "What is the capital of France?",
		},
	],
});

console.log(response.choices[0].message.content);

与 OpenAI JS 客户端类似,InferenceClient 可用于在任何兼容 OpenAI REST API 的端点上运行 Chat Completion 推理。

运行测试

HF_TOKEN="your access token" pnpm run test

寻找合适的模型

我们有一个信息丰富的文档项目,名为 Tasks,用于列出每个任务可用的模型,并详细解释每个任务的工作原理。

它还包含演示、示例输出以及其他资源,方便您更深入地了解机器学习方面的内容。

依赖

  • @huggingface/tasks : 仅类型定义
Update on GitHub