推理提供商文件

如何在 Hub 上註冊為推理服務提供商?

Hugging Face's logo
加入 Hugging Face 社群

並獲得增強的文件體驗

開始使用

如何在 Hub 上註冊為推理服務提供商?

-想在 Hugging Face Hub 上列出您的推理服務提供商?請與我們聯絡!

請在社交網路上或此處在 Hub 上聯絡我們。

本指南詳細介紹了在 Hub 上註冊為推理服務提供商的步驟,並提供了實施指導。

  1. 實施標準任務 API - 遵循我們的任務 API 架構以實現相容性(請參閱先決條件)。
  2. 提交 JS 客戶端整合 PR - 將您的提供商新增到huggingface.js(請參閱JS 客戶端整合)。
  3. 註冊模型對映 - 使用我們的模型對映 API 將您的模型連結到 Hub 模型(請參閱模型對映 API)。
  4. 實施計費端點 - 提供用於計費的 API(請參閱計費)。
  5. 提交 Python 客戶端整合 PR - 將您的提供商新增到huggingface_hub(請參閱Python 客戶端整合)。
  6. 在伺服器端註冊您的提供商並提供圖示 - 聯絡我們以在伺服器端新增您的提供商並提供您的 SVG 圖示。
  7. 在您這邊建立文件 - 新增文件並在您這邊進行大量溝通。
  8. 新增文件頁面 - 在此儲存庫 (huggingface/hub-docs) 中開啟一個 Pull Request,以在文件中新增提供商特定的頁面。
  9. 分享分享分享 多做宣傳,讓您的整合儘可能成功!

1. 先決條件

如果您的實現嚴格遵循 LLM 和 VLM 的 OpenAI API,您可能可以跳過本節大部分內容。在這種情況下,只需在huggingface.js上開啟一個 PR 進行註冊即可。

理解整合的第一步是檢視位於huggingface.js倉庫中的 JS 推理客戶端。

這是驅動模型頁面上推理小部件的客戶端,也是下游(用於 Python SDK,用於生成程式碼片段等)的藍圖實現。

什麼是任務

您將看到推理方法(`textToImage`、`chatCompletion`等)的名稱與任務名稱非常相似。任務,在 HF 生態系統中也稱為 `pipeline_tag`,是模型的型別(基本上是模型具有的輸入和輸出型別),例如“text-generation”或“text-to-image”。它在模型頁面上顯眼地標示著,在這裡:

所有可能任務的列表可以在https://huggingface.co/tasks找到,JS 方法名稱列表則記錄在https://github.com/huggingface/huggingface.js/tree/main/packages/inference的 README 中。

請注意,`chatCompletion` 是一個例外,因為它本身不是 `pipeline_tag`。相反,它包含 `pipeline_tag="text-generation"` 或 `pipeline_tag="image-text-to-text"` 並被標記為“對話型”的模型。

任務 API 架構

對於每種任務型別,我們強制執行 API 架構,以便終端使用者更容易互換使用不同的模型。為了相容,您的第三方 API 必須遵循我們期望 HF 模型頁面上每種管道任務型別的“標準”API 形狀。

對於 LLM 來說,這不是問題,因為大家都已經趨同於 OpenAI API,但對於“文字到影像”或“自動語音識別”等其他任務來說,可能更為棘手,因為沒有標準的 API。

例如,您可以在此處找到文字轉語音的預期架構:https://github.com/huggingface/huggingface.js/packages/src/tasks/text-to-speech/spec/input.json#L4,其他受支援的任務也類似。如果您的 API 在給定任務上與 HF 不同,這不是問題:您可以調整 `huggingface.js` 中的程式碼以能夠呼叫您的模型,即提供某種引數名稱和輸出名稱的“轉換”。但是,API 規範不應是模型特定的,而應是任務特定的。執行 JS 程式碼並新增一些測試以確保它執行良好。我們可以幫助完成此步驟!

2. JS 客戶端整合

在進行下一步之前,請確保您已實施必要的程式碼以與 JS 客戶端整合並徹底測試您的實現。以下是需要遵循的步驟:

實現提供商幫助器 (JS)

在 `packages/inference/src/providers/{provider_name}.ts` 下建立一個新檔案,並複製貼上以下程式碼片段。

import { TaskProviderHelper } from "./providerHelper";

export class MyNewProviderTask extends TaskProviderHelper {

	constructor() {
		super("your-provider-name", "your-api-base-url", "task-name");
	}

    override prepareHeaders(params: HeaderParams, binary: boolean): Record<string, string> {
        // Override the headers to use for the request.
        return super.prepareHeaders(params, binary);
    }

	makeRoute(params: UrlParams): string {
        // Return the route to use for the request. e.g. /v1/chat/completions route is commonly use for chat completion.
		throw new Error("Needs to be implemented");
	}

	preparePayload(params: BodyParams): Record<string, unknown> {
        // Return the payload to use for the request, as a dict.
		throw new Error("Needs to be implemented");
	}

	getResponse(response: unknown, outputType?: "url" | "blob"): string | Promise<Blob>{
		// Return the response in the expected format.
        throw new Error("Needs to be implemented");
    }
}

實現需要自定義處理的方法。檢視基礎實現以檢查預設行為。如果您不需要覆蓋某個方法,只需將其刪除即可。您必須至少定義 `makeRoute`、`preparePayload` 和 `getResponse`。

如果提供商支援需要不同實現方式的多個任務,請為每個任務建立專門的子類,遵循現有提供商實現中使用的模式,例如Together AI 提供商實現

對於文字生成和對話任務,您可以分別繼承 `BaseTextGenerationTask` 和 `BaseConversationalTask`(在providerHelper.ts中定義),並在需要時覆蓋這些方法。示例可以在CerebrasFireworks提供商實現中找到。

註冊提供商

前往packages/inference/src/lib/getProviderHelper.ts並將您的提供商新增到 `PROVIDERS`。您還需要將您的提供商新增到packages/inference/src/types.ts中的 `INFERENCE_PROVIDERS` 列表。請儘量遵循字母順序。

更新 `packages/inference` 目錄中的README.md,將您的提供商包含在支援的提供商列表和支援的模型連結列表中。

3. 模型對映 API

恭喜!您現在擁有一個 JS 實現,可以成功地在您的基礎設施上進行推理呼叫!是時候與 Hub 集成了!

第一步是使用模型對映 API 註冊支援的 HF 模型。

要繼續此步驟,我們必須在伺服器端啟用您的帳戶。請確保您的公司在 Hub 上有一個組織,並將其升級為團隊或企業計劃。

註冊對映項

POST /api/partners/{provider}/models

建立一個新的對映項,其內容(JSON 編碼)如下:

{
    "task": "WidgetType", // required
    "hfModel": "string", // required: the name of the model on HF: namespace/model-name
    "providerModel": "string", // required: the partner's "model id" i.e. id on your side
    "status": "live" | "staging" // Optional: defaults to "staging". "staging" models are only available to members of the partner's org, then you switch them to "live" when they're ready to go live
}
  • `task`,在 HF 生態系統中也稱為 `pipeline_tag`,是模型型別/API 型別(示例:“text-to-image”、“text-generation”,但對於聊天模型,您應該使用“conversational”)
  • `hfModel` 是 Hub 端的模型 ID。
  • `providerModel` 是您這邊的模型 ID(可以相同也可以不同。通常,我們鼓勵您也使用 HF 模型 ID,但這取決於您)。

此路由的輸出是一個對映 ID,您以後可以使用它來更新對映的狀態或刪除它。

身份驗證

您需要擁有*提供商* Hub 組織(例如 TogetherAI 的https://huggingface.co/togethercomputer)的**寫入**許可權才能訪問此端點。

驗證

該端點驗證:

  • `hfModel` 確實是 `pipeline_tag == task` 或者 `task` 是“對話式”且模型相容(即 `pipeline_tag` 是“text-generation”或“image-text-to-text”並且模型被標記為“對話式”)。
  • 對映建立後(非同步),我們會自動測試合作伙伴 API 是否正確處理了針對相關任務的 huggingface.js/inference 呼叫,確保 API 規範有效。請參閱下面的自動驗證部分。

使用標籤過濾器將多個 HF 模型對映到單個推理端點

我們還支援根據 HF 模型的 `tags` 進行對映。使用標籤過濾器,您可以自動將多個 HF 模型對映到您這邊的單個推理端點。例如,任何同時標記有 `lora` 和 `base_model:adapter:black-forest-labs/FLUX.1-dev` 的模型都可以對映到您的 Flux-dev LoRA 推理端點。

重要提示:確保 JS 客戶端庫可以處理您提供商的 LoRA 權重。請檢視fal 的實現以獲取更多詳細資訊。

API 如下:

POST /api/partners/{provider}/models

建立一個新的對映項,其內容(JSON 編碼)如下:

{
    "type": "tag-filter", // required
    "task": "WidgetType", // required
    "tags": ["string"], // required: any HF model with all of those tags will be mapped to providerModel
    "providerModel": "string", // required: the partner's "model id" i.e. id on your side
    "adapterType": "lora", // required: only "lora" is supported at the moment
    "status": "live" | "staging" // Optional: defaults to "staging". "staging" models are only available to members of the partner's org, then you switch them to "live" when they're ready to go live
}
  • `task`,在 HF 生態系統中也稱為 `pipeline_tag`,是模型型別/API 型別(示例:“text-to-image”、“text-generation”,但對於聊天模型,您應該使用“conversational”)
  • `tags` 是要匹配的模型標籤集。例如,要匹配 Flux 的所有 LoRA,您可以使用:`["lora", "base_model:adapter:black-forest-labs/FLUX.1-dev"]`
  • `providerModel` 是您這邊的模型 ID(可以與 HF 模型 ID 相同或不同)。
  • `adapterType` 是一個文字值,幫助客戶端庫解釋如何呼叫您的 API。目前唯一支援的值是 `“lora”`。

此路由的輸出是一個對映 ID,您以後可以使用它來更新對映的狀態或刪除它。

刪除對映項

DELETE /api/partners/{provider}/models/{mapping ID}

其中 `mapping ID` 是建立時獲得的對映的 `_id` 欄位。您也可以從列出整個對映 API 端點檢索它。

更新對映項的狀態

呼叫此 HTTP PUT 端點

PUT /api/partners/{provider}/models/{mapping ID}/status

包含以下正文(JSON 編碼)

{
    "status": "live" | "staging" // The new status, one of "staging" or "live"
}   

其中 `mapping ID` 是建立時獲得的對映的 `_id` 欄位。您也可以從列出整個對映 API 端點檢索它。

列出整個對映

GET /api/partners/{provider}/models?status=staging|live

這會從資料庫中獲取所有對映項。為了清晰起見,輸出按任務分組。

這是公開可訪問的。預設情況下保持透明很有用,它有助於除錯客戶端 SDK 等。

以下是響應示例:

{
    "text-to-image": {
        "black-forest-labs/FLUX.1-Canny-dev": {
            "_id": "xxxxxxxxxxxxxxxxxxxxxxxx",
            "providerId": "black-forest-labs/FLUX.1-canny",
            "status": "live"
        },
        "black-forest-labs/FLUX.1-Depth-dev": {
            "_id": "xxxxxxxxxxxxxxxxxxxxxxxx",
            "providerId": "black-forest-labs/FLUX.1-depth",
            "status": "live"
        },
        "tag-filter=base_model:adapter:stabilityai/stable-diffusion-xl-base-1.0,lora": {
            "_id": "xxxxxxxxxxxxxxxxxxxxxxxx",
            "status": "live",
            "providerId": "sdxl-lora-mutualized",
            "adapterType": "lora",
            "tags": [
                "base_model:adapter:stabilityai/stable-diffusion-xl-base-1.0",
                "lora"
            ]
        }
    },
    "conversational": {
        "deepseek-ai/DeepSeek-R1": {
            "_id": "xxxxxxxxxxxxxxxxxxxxxxxx",
            "providerId": "deepseek-ai/DeepSeek-R1",
            "status": "live"
        }
    },
    "text-generation": {
        "meta-llama/Llama-2-70b-hf": {
            "_id": "xxxxxxxxxxxxxxxxxxxxxxxx",
            "providerId": "meta-llama/Llama-2-70b-hf",
            "status": "live"
        },
        "mistralai/Mixtral-8x7B-v0.1": {
            "_id": "xxxxxxxxxxxxxxxxxxxxxxxx",
            "providerId": "mistralai/Mixtral-8x7B-v0.1",
            "status": "live"
        }
    }
}

自動驗證

一旦透過 API 建立了對映,Hugging Face 會執行定期自動化測試,以確保對映的端點正常執行。

每個模型每 6 小時透過對您的服務進行 API 呼叫來測試。如果測試成功,模型將保持活動狀態並繼續定期測試。但是,如果測試失敗(例如,您的服務在推理請求期間返回 HTTP 錯誤狀態),提供商將暫時從活動提供商列表中刪除。

失敗的對映每小時重新測試一次。此外,更新模型對映的狀態會觸發即時驗證測試。

驗證過程檢查以下內容:

  • 推理 API 可訪問,並且 HTTP 呼叫成功。
  • 輸出格式與 Hugging Face JavaScript 推理客戶端相容。
  • 滿足延遲要求
    • 對於對話模型和文字模型:在 5 秒以內(流式模式下首次生成令牌的時間)。
    • 對於其他任務:在 30 秒以內。

對於大型語言模型(LLMs),還會進行額外的行為測試

  • 工具呼叫支援。
  • 結構化輸出支援。

這些測試涉及向模型傳送特定的推理請求並驗證響應是否符合預期格式。

4. 計費

對於路由請求(見下圖),即使用者透過 HF 進行身份驗證時,我們的意圖是使用者只需支付標準提供商 API 費率。我們不收取額外費用,直接將提供商成本傳遞給使用者。有關定價結構的更多詳細資訊,請參閱定價頁面

我們提供了一種更簡單的方法來計算此成本並向我們的使用者收費,即要求您透過您自己託管的 HTTP API 為每個請求提供成本。

HTTP API 規範

我們要求您公開一個支援 HTTP POST 請求的 API。請求正文是一個 JSON 編碼的物件,其中包含我們請求成本的請求 ID 列表。身份驗證系統應與您的推理服務相同;例如,一個 bearer token。

POST {your URL here}
Authorization: {authentication info - eg "Bearer token"}
Content-Type: application/json

{
    "requestIds": [
        "deadbeef0",
        "deadbeef1",
        "deadbeef2",
        "deadbeef3"
    ]
}

響應也是 JSON 編碼的。響應包含一個物件陣列,指定請求的 ID 及其以納美元 (10^-9 USD) 為單位的成本。

HTTP/1.1 200 OK
Content-Type: application/json

{
    "requests": [
        { "requestId": "deadbeef0", "costNanoUsd": 100 },
        { "requestId": "deadbeef1", "costNanoUsd": 100 },
        { "requestId": "deadbeef2", "costNanoUsd": 100 },
        { "requestId": "deadbeef3", "costNanoUsd": 100 }
    ]
}

價格單位

我們要求價格是一個非負整數,單位是納美元(10^-9 美元)。

如何定義請求 ID

對於您服務的每個請求/生成,您都應該定義一個唯一的請求(或響應)ID,並將其作為響應頭提供。我們將使用此 ID 作為上述計費 API 的請求 ID。

作為這些要求的一部分,請告知我們您的標頭名稱。如果您還沒有,我們建議使用 `Inference-Id` 名稱,它應該包含一個 UUID 字串。

示例:在推理響應中定義 `Inference-Id` 標頭。

POST /v1/chat/completions
Content-Type: application/json
[request headers]
[request body]
------
HTTP/1.1 200 OK
Content-Type: application/json
[other request headers]
Inference-Id: unique-id-00131
[response body]

5. Python 客戶端整合

在將新的提供商新增到 `huggingface_hub` Python 庫之前,請確保所有之前的步驟都已完成並且 Hub 上的一切都正常執行。Python 庫中的支援是第二步。

實現提供程式助手 (Python)

在 `src/huggingface_hub/inference/_providers/{provider_name}.py` 下建立一個新檔案,並複製貼上以下程式碼片段。

實現需要自定義處理的方法。檢查基本實現以檢視預設行為。如果您不需要覆蓋某個方法,只需將其刪除即可。至少必須覆蓋 `_prepare_payload_as_dict` 或 `_prepare_payload_as_bytes` 中的一個。

如果提供商支援多個需要不同實現的任務,請為每個任務建立專門的子類,遵循 fal_ai.py 中所示的模式。

對於文字生成和對話任務,可以直接繼承自 BaseTextGenerationTask 和 BaseConversationalTask(在 _common.py 中定義),並在需要時覆蓋這些方法。示例可以在 fireworks_ai.py 和 together.py 中找到。

from typing import Any, Dict, Optional, Union

from ._common import TaskProviderHelper


class MyNewProviderTaskProviderHelper(TaskProviderHelper):
    def __init__(self):
        """Define high-level parameters."""
        super().__init__(provider=..., base_url=..., task=...)

    def get_response(
        self,
        response: Union[bytes, Dict],
        request_params: Optional[RequestParameters] = None,
    ) -> Any:
        """
        Return the response in the expected format.

        Override this method in subclasses for customized response handling."""
        return super().get_response(response)

    def _prepare_headers(self, headers: Dict, api_key: str) -> Dict:
        """Return the headers to use for the request.

        Override this method in subclasses for customized headers.
        """
        return super()._prepare_headers(headers, api_key)

    def _prepare_route(self, mapped_model: str, api_key: str) -> str:
        """Return the route to use for the request.

        Override this method in subclasses for customized routes.
        """
        return super()._prepare_route(mapped_model)

    def _prepare_payload_as_dict(self, inputs: Any, parameters: Dict, mapped_model: str) -> Optional[Dict]:
        """Return the payload to use for the request, as a dict.

        Override this method in subclasses for customized payloads.
        Only one of `_prepare_payload_as_dict` and `_prepare_payload_as_bytes` should return a value.
        """
        return super()._prepare_payload_as_dict(inputs, parameters, mapped_model)

    def _prepare_payload_as_bytes(
        self, inputs: Any, parameters: Dict, mapped_model: str, extra_payload: Optional[Dict]
    ) -> Optional[bytes]:
        """Return the body to use for the request, as bytes.

        Override this method in subclasses for customized body data.
        Only one of `_prepare_payload_as_dict` and `_prepare_payload_as_bytes` should return a value.
        """
        return super()._prepare_payload_as_bytes(inputs, parameters, mapped_model, extra_payload)

註冊提供商

新增測試

6. 新增提供商文件

在 Hugging Face 文件中為您的提供商建立一個專用文件頁面。此頁面應包含對您的提供商服務的簡潔描述,突出使用者的好處,設定對效能或功能的期望,幷包含任何相關細節,例如定價模型或資料保留政策。實質上,提供對終端使用者有價值的任何資訊。

以下是新增文件頁面的方法:

  • 提供您的徽標:您可以直接將您的徽標檔案(單獨的亮色和暗色模式版本)傳送給我們。這通常是最簡單的方法。或者,如果您願意,您可以在huggingface/documentation-images儲存庫中開啟一個 PR。如果您選擇開啟 PR:
    • 徽標必須是 `.png` 格式。
    • 將其命名為 `{provider-name}-light.png` 和 `{provider-name}-dark.png`。
    • 請在 PR 上標記 `Wauplin` 和 `celinah`。
  • 建立文件檔案
    • 使用現有提供商頁面作為模板。例如,請檢視Fal AI的模板。
    • 該檔案應位於 `scripts/inference-providers/templates/providers/{your-provider-name}.handlebars` 下。
  • 提交文件 PR
    • 新增您的新 `{provider-name}.handlebars` 檔案。
    • 更新合作伙伴表格以包含您的公司或產品。
    • 更新 `docs/inference-providers/` 目錄中的 `_toctree.yml` 檔案,將您的新文件頁面包含在“提供商”部分,並保持字母順序。
    • 更新 `scripts/inference-providers/scripts/generate.ts` 檔案,將您的提供商包含在 `PROVIDERS_HUB_ORGS` 和 `PROVIDERS_URLS` 常量中,並保持字母順序。
    • 在 `scripts/inference-providers` 倉庫的根目錄下執行 `pnpm install`(如果您尚未安裝)然後執行 `pnpm run generate` 以生成文件。
    • 提交所有更改,包括手動編輯的檔案(提供商頁面、`_toctree.yml`、合作伙伴表)和指令碼生成的檔案。
    • 當您開啟 PR 時,請標記 @Wauplin、@SBrandeis、@julien-c 和 @hanouticelina 進行審查。如果您在這些步驟中需要任何幫助,請隨時聯絡——我們隨時為您提供幫助!

常見問題

問題:預設情況下,我們在設定頁面中按什麼順序列出提供商?

答案:預設排序是按過去 7 天內 HF 路由的總請求數。此順序決定了模型頁面上的小部件將優先使用哪個提供商(但使用者自定義的順序優先)。

< > 在 GitHub 上更新

© . This site is unofficial and not affiliated with Hugging Face, Inc.