Hub Python Library documentation

서버에서 추론 실행

You are viewing main version, which requires installation from source. If you'd like regular pip install, checkout the latest stable version (v2.4.0).
Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

서버에서 추론 실행

Inference는 학습된 모델을 사용하여 새로운 데이터에 대한 예측을 수행하는 과정입니다. 이 과정은 계산 집약적일 수 있으므로, 전용 또는 외부 서비스에서 실행하는 것이 흥미로운 옵션이 될 수 있습니다. huggingface_hub 라이브러리는 Hugging Face Hub에 호스팅된 모델에 대해 여러 서비스에서 추론을 실행하기 위한 통합 인터페이스를 제공합니다:

  1. Inference Providers: 서버리스 추론 파트너가 제공하는 수백 개의 머신러닝 모델에 대한 간소화되고 통합된 접근 방식입니다. 이 새로운 접근 방식은 기존의 Serverless Inference API를 기반으로 하며, 세계 수준의 제공업체 덕분에 더 많은 모델, 향상된 성능, 그리고 더 높은 신뢰성을 제공합니다. 지원되는 제공업체 목록은 문서를 참조하세요.
  2. Inference Endpoints: 모델을 프로덕션에 쉽게 배포할 수 있는 제품입니다. 추론은 사용자가 선택한 클라우드 제공자의 전용, 완전 관리형 인프라에서 Hugging Face에 의해 실행됩니다.
  3. 로컬 엔드포인트: 클라이언트를 이러한 로컬 엔드포인트에 연결하여 llama.cpp, Ollama, vLLM, LiteLLM, 또는 Text Generation Inference (TGI)와 같은 로컬 추론 서버로 추론을 실행할 수도 있습니다.

InferenceClient는 API에 HTTP 호출을 수행하는 Python 클라이언트입니다. 선호하는 도구(curl, postman 등)를 사용하여 직접 HTTP 호출을 수행하려면 Inference Providers 문서 또는 Inference Endpoints 문서 페이지를 참조하세요.

웹 개발을 위해 JS 클라이언트가 출시되었습니다. 게임 개발에 관심이 있으시다면, 우리의 C# 프로젝트를 살펴보세요.

시작하기

텍스트-이미지 생성 작업으로 시작해 보겠습니다:

>>> from huggingface_hub import InferenceClient

# Example with an external provider (e.g. replicate)
>>> replicate_client = InferenceClient(
    provider="replicate",
    api_key="my_replicate_api_key",
)
>>> replicate_image = replicate_client.text_to_image(
    "A flying car crossing a futuristic cityscape.",
    model="black-forest-labs/FLUX.1-schnell",
)
>>> replicate_image.save("flying_car.png")

위 예제에서는 서드파티 제공자 Replicate를 사용하여 InferenceClient를 초기화했습니다. 제공자를 사용할 때는 사용하려는 모델을 지정해야 합니다. 모델 id는 서드파티 제공자의 모델 id가 아니라 Hugging Face Hub의 모델 id여야 합니다. 우리의 예제에서는 텍스트 프롬프트로부터 이미지를 생성했습니다. 반환 값은 파일로 저장할 수 있는 PIL.Image 객체입니다. 자세한 내용은 text_to_image() 문서를 확인하세요.

이제 chat_completion() API를 사용하는 예를 살펴보겠습니다. 이 작업은 LLM을 사용하여 메시지 목록에서 응답을 생성합니다:

>>> from huggingface_hub import InferenceClient
>>> messages = [
    {
        "role": "user",
        "content": "What is the capital of France?",
    }
]
>>> client = InferenceClient(
    provider="together",
    model="meta-llama/Meta-Llama-3-8B-Instruct",
    api_key="my_together_api_key",
)
>>> client.chat_completion(messages, max_tokens=100)
ChatCompletionOutput(
    choices=[
        ChatCompletionOutputComplete(
            finish_reason="eos_token",
            index=0,
            message=ChatCompletionOutputMessage(
                role="assistant", content="The capital of France is Paris.", name=None, tool_calls=None
            ),
            logprobs=None,
        )
    ],
    created=1719907176,
    id="",
    model="meta-llama/Meta-Llama-3-8B-Instruct",
    object="text_completion",
    system_fingerprint="2.0.4-sha-f426a33",
    usage=ChatCompletionOutputUsage(completion_tokens=8, prompt_tokens=17, total_tokens=25),
)

위 예시에서는 서드파티 제공자(Together AI)를 사용하고, 사용할 모델을 지정했습니다("meta-llama/Meta-Llama-3-8B-Instruct"). 그런 다음 완료할 메시지 목록(여기서는 단일 질문)을 제공하고, API에 추가 매개변수(max_token=100)를 전달했습니다. 출력은 OpenAI 사양을 따르는 ChatCompletionOutput 객체입니다. 생성된 콘텐츠는 output.choices[0].message.content로 접근할 수 있습니다. 자세한 내용은 chat_completion() 문서를 참고하세요.

API는 단순하게 설계되어 있습니다. 모든 매개변수와 옵션이 최종 사용자에게 제공되거나 설명되지는 않습니다. 각 작업에 사용할 수 있는 모든 매개변수에 대해 자세히 알고 싶다면 이 페이지를 확인해 보세요.

특정 프로바이더 사용

특정 제공자를 사용하려면 클라이언트를 초기화할 때 지정할 수 있습니다. 기본값은 “auto”이며, 이는 https://hf.co/settings/inference-providers에서 사용자가 지정한 순서대로 정렬된 모델에 사용 가능한 제공자 중 첫 번째를 선택합니다. 지원되는 제공자 목록은 Supported providers and tasks 섹션을 참조하세요.

>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient(provider="replicate", api_key="my_replicate_api_key")

특정 모델 사용

특정 모델을 사용하려면 어떻게 해야 하나요? 매개변수로 지정하거나 인스턴스 수준에서 직접 지정할 수 있습니다:

>>> from huggingface_hub import InferenceClient
# Initialize client for a specific model
>>> client = InferenceClient(provider="together", model="meta-llama/Llama-3.1-8B-Instruct")
>>> client.text_to_image(...)
# Or use a generic client but pass your model as an argument
>>> client = InferenceClient(provider="together")
>>> client.text_to_image(..., model="meta-llama/Llama-3.1-8B-Instruct")

“hf-inference” 제공자를 사용할 때, 각 작업에는 Hub에서 사용할 수 있는 100만 개 이상의 모델 중 권장 모델이 함께 제공됩니다. 그러나 이 권장 사항은 시간이 지남에 따라 변경될 수 있으므로, 사용할 모델을 결정했다면 명시적으로 모델을 설정하는 것이 좋습니다. 서드파티 제공자의 경우, 해당 제공자와 호환되는 모델을 항상 지정해야 합니다.

Hub의 Models 페이지를 방문하여 Inference Providers를 통해 사용할 수 있는 모델을 탐색해 보세요.

Inference Endpoints 사용

위에서 살펴본 예제는 추론 제공자를 사용합니다. 이러한 방식은 프로토타이핑 및 빠른 테스트에 매우 유용합니다. 하지만 모델을 프로덕션 환경에 배포할 준비가 되면 전용 인프라를 사용해야 합니다. 이때 Inference Endpoints가 활용됩니다. 이를 통해 어떤 모델이든 배포하고 이를 비공개 API로 노출할 수 있습니다. 배포가 완료되면 이전과 동일한 코드를 사용하여 연결할 수 있는 URL을 받게 되며, 이때 변경하는 것은 model 파라미터뿐입니다:

>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient(model="https://uu149rez6gw9ehej.eu-west-1.aws.endpoints.huggingface.cloud/deepfloyd-if")
# or
>>> client = InferenceClient()
>>> client.text_to_image(..., model="https://uu149rez6gw9ehej.eu-west-1.aws.endpoints.huggingface.cloud/deepfloyd-if")

URL과 provider를 동시에 지정할 수 없으며, 둘은 상호 배타적입니다. URL은 배포된 엔드포인트에 직접 연결하는 데 사용됩니다.

로컬 엔드포인트 사용

InferenceClient를 사용하여 자체 머신에서 실행 중인 로컬 추론 서버(llama.cpp, vllm, litellm server, TGI, mlx 등)로 채팅 완성을 수행할 수 있습니다. API는 OpenAI API와 호환되어야 합니다.

>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient(model="http://localhost:8080")

>>> response = client.chat.completions.create(
...     messages=[
...         {"role": "user", "content": "What is the capital of France?"}
...     ],
...     max_tokens=100
... )
>>> print(response.choices[0].message.content)

OpenAI Python 클라이언트와 마찬가지로, InferenceClient는 OpenAI REST API 호환 엔드포인트에서 Chat Completion 추론을 실행하는 데 사용할 수 있습니다.

인증

인증은 두 가지 방식으로 수행할 수 있습니다:

Hugging Face를 통해 라우팅 : Hugging Face를 프록시로 사용하여 서드파티 제공업체에 액세스합니다. 호출은 Hugging Face의 인프라를 통해 제공업체 키를 사용하여 라우팅되며, 사용량은 Hugging Face 계정에 직접 청구됩니다.

User Access Token을 사용하여 인증할 수 있습니다. api_key 매개변수를 사용하여 Hugging Face 토큰을 직접 제공할 수 있습니다:

>>> client = InferenceClient(
    provider="replicate",
    api_key="hf_****"  # Your HF token
)

api_key를 전달하지 않으면 클라이언트는 로컬 머신에 저장된 토큰을 찾아 사용하려고 시도합니다. 이는 이전에 로그인한 경우 일반적으로 발생하는 동작입니다. 로그인에 대한 자세한 내용은 Authentication Guide를 참조하세요.

>>> client = InferenceClient(
    provider="replicate",
    token="hf_****"  # Your HF token
)

프로바이더 직접 액세스: 자체 API 키를 사용하여 프로바이더의 서비스에 직접 상호작용합니다:

>>> client = InferenceClient(
    provider="replicate",
    api_key="r8_****"  # Your Replicate API key
)

자세한 내용은 Inference Providers 가격 문서를 참조하세요.

지원되는 제공자 및 작업

InferenceClient의 목표는 모든 프로바이더에서 Hugging Face 모델로 추론을 실행할 수 있는 가장 쉬운 인터페이스를 제공하는 것입니다. 가장 일반적인 작업을 지원하는 간단한 API를 갖추고 있습니다. 아래 표는 각 프로바이더가 어떤 작업을 지원하는지 보여줍니다:

작업BasetenCerebrasCohereDeepInfrafal-aiFeatherless AIFireworks AIGroqHF InferenceNovita AINscaleOVHcloud AI Endpoints공개 AI복제ScalewayTogetherWavespeedZai
audio_classification()❌❌❌❌❌❌❌❌✅❌❌❌❌❌❌❌❌❌
audio_to_audio()❌❌❌❌❌❌❌❌✅❌❌❌❌❌❌❌❌❌
automatic_speech_recognition()❌❌❌✅✅❌❌❌✅❌❌❌❌✅❌❌❌❌
chat_completion()✅✅✅✅❌✅✅✅✅✅✅✅✅❌✅✅❌✅
document_question_answering()❌❌❌❌❌❌❌❌✅❌❌❌❌❌❌❌❌❌
feature_extraction()❌❌❌✅❌❌❌❌✅❌❌❌❌❌✅✅❌❌
fill_mask()❌❌❌❌❌❌❌❌✅❌❌❌❌❌❌❌❌❌
image_classification()❌❌❌❌❌❌❌❌✅❌❌❌❌❌❌❌❌❌
image_segmentation()❌❌❌❌✅❌❌❌✅❌❌❌❌❌❌❌❌❌
image_to_image()❌❌❌❌✅❌❌❌✅❌❌❌❌✅❌✅✅❌
image_to_video()❌❌❌❌✅❌❌❌❌❌❌❌❌❌❌✅✅❌
image_to_text()❌❌❌❌❌❌❌❌✅❌❌❌❌❌❌❌❌❌
object_detection()❌❌❌❌❌❌❌❌✅❌❌❌❌❌❌❌❌❌
question_answering()❌❌❌❌❌❌❌❌✅❌❌❌❌❌❌❌❌❌
sentence_similarity()❌❌❌❌❌❌❌❌✅❌❌❌❌❌❌❌❌❌
summarization()❌❌❌❌❌❌❌❌✅❌❌❌❌❌❌❌❌❌
table_question_answering()❌❌❌❌❌❌❌❌✅❌❌❌❌❌❌❌❌❌
text_classification()❌❌❌❌❌❌❌❌✅❌❌❌❌❌❌❌❌❌
text_generation()❌❌❌✅❌✅❌❌✅✅❌❌❌❌❌✅❌❌
text_to_image()❌❌❌❌✅❌❌❌✅❌✅❌❌✅❌✅✅✅
text_to_speech()❌❌❌✅✅❌❌❌✅❌❌❌❌✅❌✅❌❌
text_to_video()❌❌❌❌✅❌❌❌❌✅❌❌❌✅❌✅✅❌
tabular_classification()❌❌❌❌❌❌❌❌✅❌❌❌❌❌❌❌❌❌
tabular_regression()❌❌❌❌❌❌❌❌✅❌❌❌❌❌❌❌❌❌
token_classification()❌❌❌❌❌❌❌❌✅❌❌❌❌❌❌❌❌❌
translation()❌❌❌❌❌❌❌❌✅❌❌❌❌❌❌❌❌❌
visual_question_answering()❌❌❌❌❌❌❌❌✅❌❌❌❌❌❌❌❌❌
zero_shot_image_classification()❌❌❌❌❌❌❌❌✅❌❌❌❌❌❌❌❌❌
zero_shot_classification()❌❌❌❌❌❌❌❌✅❌❌❌❌❌❌❌❌❌

각 작업에 대해 자세히 알아보려면 Tasks 페이지를 확인하세요.

OpenAI 호환성

chat_completion 작업은 OpenAI의 Python 클라이언트 문법을 따릅니다. 이것이 사용자에게 무엇을 의미할까요? OpenAI API를 사용해 본 경험이 있다면, 코드 2줄만 수정하면 huggingface_hub.InferenceClient로 전환하여 오픈소스 모델을 사용할 수 있습니다!

- from openai import OpenAI
+ from huggingface_hub import InferenceClient

- client = OpenAI(
+ client = InferenceClient(
    base_url=...,
    api_key=...,
)


output = client.chat.completions.create(
    model="meta-llama/Meta-Llama-3-8B-Instruct",
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "Count to 10"},
    ],
    stream=True,
    max_tokens=1024,
)

for chunk in output:
    print(chunk.choices[0].delta.content)

그리고 끝입니다! 필수적인 변경 사항은 from openai import OpenAI를 from huggingface_hub import InferenceClient로, client = OpenAI(...)를 client = InferenceClient(...)로 교체하는 것입니다. model 매개변수에 모델 id를 전달하여 Hugging Face Hub의 LLM 모델 중 아무거나 선택할 수 있습니다. 지원되는 모델 목록은 여기에서 확인하세요. 인증을 위해 유효한 User Access Token을 api_key로 전달하거나 huggingface_hub를 사용하여 인증해야 합니다(인증 가이드 참고).

모든 입력 매개변수와 출력 형식이 엄격하게 동일합니다. 특히 stream=True를 전달하여 토큰이 생성되는 대로 수신할 수 있습니다. 또한 AsyncInferenceClient를 사용하여 asyncio로 추론을 실행할 수도 있습니다:

import asyncio
- from openai import AsyncOpenAI
+ from huggingface_hub import AsyncInferenceClient

- client = AsyncOpenAI()
+ client = AsyncInferenceClient()

async def main():
    stream = await client.chat.completions.create(
        model="meta-llama/Meta-Llama-3-8B-Instruct",
        messages=[{"role": "user", "content": "Say this is a test"}],
        stream=True,
    )
    async for chunk in stream:
        print(chunk.choices[0].delta.content or "", end="")

asyncio.run(main())

InferenceClient를 OpenAI의 클라이언트 대신 사용하는 이유는 무엇일까요? 몇 가지 이유가 있습니다:

  1. InferenceClient는 Hugging Face 서비스에 맞게 구성됩니다. Inference Providers로 모델을 실행하려면 base_url을 제공할 필요가 없습니다. 또한, 머신이 이미 올바르게 로그인되어 있다면 token 또는 api_key를 제공할 필요가 없습니다.
  2. InferenceClient는 Text-Generation-Inference(TGI)와 transformers 프레임워크 모두에 최적화되어 있어, 항상 최신 업데이트와 동일한 수준을 유지할 수 있습니다.
  3. InferenceClient는 Inference Endpoints 서비스와 통합되어 Inference Endpoint를 시작하고, 상태를 확인하며, 해당 Endpoint에서 추론을 실행하는 과정을 더 쉽게 만들어 줍니다. 자세한 내용은 Inference Endpoints 가이드를 참고하세요.

InferenceClient.chat.completions.create는 InferenceClient.chat_completion의 별칭입니다. 자세한 내용은 chat_completion()의 패키지 참조를 확인하세요. 클라이언트를 초기화할 때 사용하는 base_url 및 api_key 매개변수도 각각 model과 token의 별칭입니다. 이러한 별칭은 OpenAI에서 InferenceClient로 전환할 때의 마찰을 줄이기 위해 정의되었습니다.

Function Calling

Function calling은 LLM이 정의된 함수나 API와 같은 외부 도구와 상호작용할 수 있도록 합니다. 이를 통해 사용자는 특정 사용 사례와 실제 작업에 맞춘 애플리케이션을 쉽게 구축할 수 있습니다. InferenceClient는 OpenAI Chat Completions API와 동일한 tool calling 인터페이스를 구현합니다. Novita를 추론 제공자로 사용하는 tool calling의 간단한 예시는 다음과 같습니다:

from huggingface_hub import InferenceClient

tools = [
        {
            "type": "function",
            "function": {
                "name": "get_weather",
                "description": "Get current temperature for a given location.",
                "parameters": {
                    "type": "object",
                    "properties": {
                        "location": {
                            "type": "string",
                            "description": "City and country e.g. Paris, France"
                        }
                    },
                    "required": ["location"],
                },
            }
        }
]

client = InferenceClient(provider="novita")

response = client.chat.completions.create(
    model="Qwen/Qwen2.5-72B-Instruct",
    messages=[
    {
        "role": "user",
        "content": "What's the weather like the next 3 days in London, UK?"
    }
    ],
    tools=tools,
    tool_choice="auto",
)

print(response.choices[0].message.tool_calls[0].function.arguments)

Function/Tool Calling을 지원하는 모델이 무엇인지 확인하려면 각 제공업체의 문서를 참조하세요.

구조화된 출력 & JSON 모드

InferenceClient는 구문적으로 유효한 JSON 응답을 위한 JSON mode와 스키마가 강제되는 응답을 위한 Structured Outputs를 지원합니다. JSON mode는 엄격한 구조 없이 기계가 읽을 수 있는 데이터를 제공하며, Structured Outputs는 유효한 JSON과 사전 정의된 스키마 준수라는 두 가지를 모두 보장하여 안정적인 다운스트림 처리를 가능하게 합니다.

JSON 모드와 Structured Outputs 모두 OpenAI API 스펙을 따릅니다. response_format 인수를 통해 활성화할 수 있습니다. Cerebras를 추론 제공자로 사용하는 Structured Outputs의 예시는 다음과 같습니다:

from huggingface_hub import InferenceClient

json_schema = {
    "name": "book",
    "schema": {
        "properties": {
            "name": {
                "title": "Name",
                "type": "string",
            },
            "authors": {
                "items": {"type": "string"},
                "title": "Authors",
                "type": "array",
            },
        },
        "required": ["name", "authors"],
        "title": "Book",
        "type": "object",
    },
    "strict": True,
}

client = InferenceClient(provider="cerebras")


completion = client.chat.completions.create(
    model="Qwen/Qwen3-32B",
    messages=[
        {"role": "system", "content": "Extract the books information."},
        {"role": "user", "content": "I recently read 'The Great Gatsby' by F. Scott Fitzgerald."},
    ],
    response_format={
        "type": "json_schema",
        "json_schema": json_schema,
    },
)

print(completion.choices[0].message)

Structured Outputs 및 JSON Mode에서 지원되는 모델이 무엇인지 확인하려면 각 제공업체의 문서를 참조하세요.

비동기 클라이언트

asyncio와 httpx2를 기반으로 한 클라이언트의 비동기 버전도 제공됩니다. 모든 비동기 API 엔드포인트는 AsyncInferenceClient를 통해 사용할 수 있습니다. 초기화 및 API는 동기 전용 버전과 완전히 동일합니다.

# Code must be run in an asyncio concurrent context.
# $ python -m asyncio
>>> from huggingface_hub import AsyncInferenceClient
>>> client = AsyncInferenceClient()

>>> image = await client.text_to_image("An astronaut riding a horse on the moon.")
>>> image.save("astronaut.png")

>>> async for token in await client.text_generation("The Huggingface Hub is", stream=True):
...     print(token, end="")
 a platform for sharing and discussing ML-related content.

asyncio 모듈에 대한 자세한 내용은 공식 문서를 참고하세요.

MCP 클라이언트

huggingface_hub 라이브러리는 이제 Model Context Protocol(MCP)을 통해 외부 Tools와 상호작용할 수 있는 기능을 Large Language Models(LLM)에 부여하도록 설계된 실험적 MCPClient를 포함합니다. 이 클라이언트는 AsyncInferenceClient를 확장하여 Tool 사용을 원활하게 통합합니다.

MCPClient는 도구를 노출하는 MCP 서버(로컬 stdio 스크립트 또는 원격 http/sse 서비스)에 연결합니다. 이 클라이언트는 이러한 도구를 LLM에 전달하며(AsyncInferenceClient를 통해) LLM이 도구를 사용하기로 결정하면 MCPClient가 MCP 서버로의 실행 요청을 관리하고 Tool의 출력을 LLM으로 되돌려 전달합니다. 이 과정에서 결과를 실시간으로 스트리밍하는 경우가 많습니다.

다음 예시에서는 Novita 추론 제공자를 통해 Qwen/Qwen2.5-72B-Instruct 모델을 사용합니다. 그런 다음 원격 MCP 서버를 추가합니다. 이 경우 SSE 서버로, Flux 이미지 생성 도구를 LLM에 사용할 수 있게 합니다.

import os

from huggingface_hub import ChatCompletionInputMessage, ChatCompletionStreamOutput, MCPClient


async def main():
    async with MCPClient(
        provider="novita",
        model="Qwen/Qwen2.5-72B-Instruct",
        api_key=os.environ["HF_TOKEN"],
    ) as client:
        await client.add_mcp_server(type="sse", url="https://evalstate-flux1-schnell.hf.space/gradio_api/mcp/sse")

        messages = [
            {
                "role": "user",
                "content": "Generate a picture of a cat on the moon",
            }
        ]

        async for chunk in client.process_single_turn_with_tools(messages):
            # Log messages
            if isinstance(chunk, ChatCompletionStreamOutput):
                delta = chunk.choices[0].delta
                if delta.content:
                    print(delta.content, end="")

            # Or tool calls
            elif isinstance(chunk, ChatCompletionInputMessage):
                print(
                    f"\nCalled tool '{chunk.name}'. Result: '{chunk.content if len(chunk.content) < 1000 else chunk.content[:1000] + '...'}'"
                )


if __name__ == "__main__":
    import asyncio

    asyncio.run(main())

더 간단한 개발을 위해 더 높은 수준의 Agent 클래스를 제공합니다. 이 ‘Tiny Agent’는 채팅 루프와 상태를 관리하여 대화형 Agent 생성을 단순화하며, 기본적으로 MCPClient를 감싸는 래퍼 역할을 합니다. MCPClient 바로 위에 구축된 단순한 while 루프가 되도록 설계되었습니다. 이러한 Agent는 명령줄에서 직접 실행할 수 있습니다:

# install latest version of huggingface_hub with the mcp extra
pip install -U huggingface_hub[mcp]
# Run an agent that uses the Flux image generation tool
tiny-agents run julien-c/flux-schnell-generator

Agent가 시작되면 연결된 MCP 서버에서 발견한 Tools를 로드하고 나열한 후, 프롬프트를 입력할 준비가 완료됩니다!

고급 팁

위 섹션에서 InferenceClient의 주요 측면을 살펴보았습니다. 이제 좀 더 고급 팁을 자세히 살펴보겠습니다.

청구

HF 사용자는 Hub에서 다양한 프로바이더를 통해 추론을 실행할 수 있는 월별 크레딧을 제공합니다. 크레딧의 양은 계정 유형(Free 또는 PRO 또는 Enterprise Hub)에 따라 달라집니다. 프로바이더의 가격표에 따라 모든 추론 요청에 대해 요금이 부과됩니다. 기본적으로 요청은 개인 계정으로 청구됩니다. 그러나 InferenceClient에 bill_to="<your_org_name>"를 전달하기만 하면 요청이 소속된 조직으로 청구되도록 청구 설정을 변경할 수 있습니다. 이를 위해 조직은 Enterprise Hub에 가입되어 있어야 합니다. 청구에 대한 자세한 내용은 이 가이드를 참고하세요.

>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient(provider="fal-ai", bill_to="openai")
>>> image = client.text_to_image(
...     "A majestic lion in a fantasy forest",
...     model="black-forest-labs/FLUX.1-schnell",
... )
>>> image.save("lion.png")

다른 사용자나 소속되지 않은 조직에 크레딧을 청구할 수 없습니다. 다른 사람에게 크레딧을 제공하려면 해당 사람과 공동 조직을 생성해야 합니다.

Timeout

Inference 호출은 상당한 시간이 소요될 수 있습니다. 기본적으로 InferenceClient는 inference가 완료될 때까지 “무한정” 대기합니다. 워크플로우에서 더 많은 제어가 필요하면 timeout 매개변수를 초 단위의 특정 값으로 설정할 수 있습니다. timeout 지연이 만료되면 InferenceTimeoutError가 발생하며, 이를 코드에서 catch할 수 있습니다:

>>> from huggingface_hub import InferenceClient, InferenceTimeoutError
>>> client = InferenceClient(timeout=30)
>>> try:
...     client.text_to_image(...)
... except InferenceTimeoutError:
...     print("Inference timed out after 30s.")

바이너리 입력

일부 작업은 바이너리 입력을 요구합니다. 예를 들어 이미지나 오디오 파일을 다룰 때입니다. 이 경우 InferenceClient는 가능한 한 관대하게 동작하여 다양한 유형을 수용합니다:

  • bytes의 원시
  • 바이너리로 열린 파일 유사 객체(with open("audio.flac", "rb") as f: ...)
  • 로컬 파일을 가리키는 경로(str 또는 Path)
  • 원격 파일(예: https://...)을 가리키는 URL(str). 이 경우 파일은 API로 전송되기 전에 로컬로 다운로드됩니다.
>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient()
>>> client.image_classification("https://upload.wikimedia.org/wikipedia/commons/thumb/4/43/Cute_dog.jpg/320px-Cute_dog.jpg")
[{'score': 0.9779096841812134, 'label': 'Blenheim spaniel'}, ...]
Update on GitHub