# 서버에서 추론 실행

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

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

> [!TIP]
> [InferenceClient](/docs/huggingface_hub/v2.5.0/ko/package_reference/inference_client#huggingface_hub.InferenceClient)는 API에 HTTP 호출을 수행하는 Python 클라이언트입니다. 선호하는 도구(curl, postman 등)를 사용하여 직접 HTTP 호출을 수행하려면 [Inference Providers](https://huggingface.co/docs/inference-providers/index) 문서 또는 [Inference Endpoints](https://huggingface.co/docs/inference-endpoints/index) 문서 페이지를 참조하세요.
>
> 웹 개발을 위해 [JS 클라이언트](https://huggingface.co/docs/huggingface.js/inference/README)가 출시되었습니다. 게임 개발에 관심이 있으시다면 [C# 프로젝트](https://github.com/huggingface/unity-api)를 참고해 보시기 바랍니다.

## 시작하기

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

```python
>>> 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](https://replicate.com/)를 사용하여 [InferenceClient](/docs/huggingface_hub/v2.5.0/ko/package_reference/inference_client#huggingface_hub.InferenceClient)를 초기화했습니다. 제공자를 사용할 때는 사용하려는 모델을 지정해야 합니다. 모델 id는 서드파티 제공자의 모델 id가 아니라 Hugging Face Hub의 모델 id여야 합니다. 예시에서는 텍스트 프롬프트로부터 이미지를 생성했습니다. 반환 값은 파일로 저장할 수 있는 `PIL.Image` 객체입니다. 자세한 내용은 [text_to_image()](/docs/huggingface_hub/v2.5.0/ko/package_reference/inference_client#huggingface_hub.InferenceClient.text_to_image) 문서를 참고하세요.

이제 [chat_completion()](/docs/huggingface_hub/v2.5.0/ko/package_reference/inference_client#huggingface_hub.InferenceClient.chat_completion) API를 사용하는 예를 살펴보겠습니다. 이 작업은 LLM을 사용하여 메시지 목록에서 응답을 생성합니다:

```python
>>> from huggingface_hub import InferenceClient
>>> messages = [
    {
        "role": "user",
        "content": "What is the capital of France?",
    }
]
>>> client = InferenceClient(
    model="deepseek-ai/DeepSeek-V4.1-Flash",
    api_key="hf_****",  # Your Hugging Face token
)
>>> client.chat_completion(messages, max_tokens=100)
ChatCompletionOutput(
    choices=[
        ChatCompletionOutputComplete(
            finish_reason="stop",
            index=0,
            message=ChatCompletionOutputMessage(
                role="assistant", content="The capital of France is **Paris**.", tool_calls=None, ...
            ),
            logprobs=None,
        )
    ],
    object="chat.completion",
    usage=ChatCompletionOutputUsage(completion_tokens=18, prompt_tokens=37, total_tokens=55, ...),
    ...
)
```

위의 예시에서 사용할 모델을 지정했습니다(`"deepseek-ai/DeepSeek-V4.1-Flash"`). 추론은 [OpenRouter](https://openrouter.ai)에 의해 구동됩니다. 각 요청은 해당 모델을 서빙하는 프로바이더로 전송되며, 해당 프로바이더가 다운되거나 레이트 리밋에 걸리면 자동으로 다른 프로바이더로 전환됩니다. 이후 완성할 메시지 목록(여기서는 단일 질문)을 제공하고 API에 추가 매개변수(`max_token=100`)를 전달했습니다. 출력은 OpenAI 사양을 따르는 `ChatCompletionOutput` 객체입니다. 생성된 콘텐츠는 `output.choices[0].message.content`로 접근할 수 있습니다. 자세한 내용은 [chat_completion()](/docs/huggingface_hub/v2.5.0/ko/package_reference/inference_client#huggingface_hub.InferenceClient.chat_completion) 문서를 참고하세요.

> [!WARNING]
> API는 단순하게 설계되어 있습니다. 모든 매개변수와 옵션이 최종 사용자에게 제공되거나 설명되지는 않습니다. 각 작업에 사용할 수 있는 모든 매개변수에 대해 자세히 알고 싶다면 [이 페이지](https://huggingface.co/docs/api-inference/detailed_parameters)를 확인해 보세요.

### 특정 프로바이더 사용

특정 제공자를 사용하려면 클라이언트를 초기화할 때 지정할 수 있습니다. 기본값은 "auto"이며, 이는 https://hf.co/settings/inference-providers 에서 사용자가 지정한 순서대로 정렬된 모델에 사용 가능한 제공자 중 첫 번째를 선택합니다. 지원되는 제공자 목록은 [Inference Providers 문서](https://huggingface.co/docs/inference-providers/index)를 참조하세요.

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

### 특정 모델 사용

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

```python
>>> from huggingface_hub import InferenceClient
# Initialize client for a specific model
>>> client = InferenceClient(provider="fal-ai", model="black-forest-labs/FLUX.1-schnell")
>>> client.text_to_image(...)
# Or use a generic client but pass your model as an argument
>>> client = InferenceClient(provider="fal-ai")
>>> client.text_to_image(..., model="black-forest-labs/FLUX.1-schnell")
```

> [!TIP]
> "hf-inference" 제공자를 사용할 때, 각 작업에는 Hub에서 사용할 수 있는 100만 개 이상의 모델 중 권장 모델이 함께 제공됩니다. 그러나 이 권장 사항은 시간이 지남에 따라 변경될 수 있으므로, 사용할 모델을 결정했다면 명시적으로 모델을 설정하는 것이 좋습니다. 제3자 제공자의 경우, 해당 제공자와 호환되는 모델을 항상 지정해야 합니다.
>
> Hub의 [Models](https://huggingface.co/models?inference=warm) 페이지를 방문하여 Inference Providers를 통해 사용할 수 있는 모델을 탐색해 보세요.

### Inference Endpoints 사용

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

```python
>>> 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](/docs/huggingface_hub/v2.5.0/ko/package_reference/inference_client#huggingface_hub.InferenceClient)를 사용하여 자체 머신에서 실행 중인 로컬 추론 서버(llama.cpp, vllm, litellm server, TGI, mlx 등)로 채팅 완성을 수행할 수 있습니다. API는 OpenAI API와 호환되어야 합니다.

```python
>>> 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)
```

> [!TIP]
> OpenAI Python 클라이언트와 마찬가지로, [InferenceClient](/docs/huggingface_hub/v2.5.0/ko/package_reference/inference_client#huggingface_hub.InferenceClient)는 OpenAI REST API 호환 엔드포인트에서 Chat Completion 추론을 실행하는 데 사용할 수 있습니다.

### 인증

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

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

[User Access Token](https://huggingface.co/docs/hub/security-tokens)을 사용하여 인증할 수 있습니다. `api_key` 매개변수를 사용하여 Hugging Face 토큰을 직접 제공할 수 있습니다:

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

`api_key`를 *전달하지 않으면* 클라이언트는 로컬 머신에 저장된 토큰을 찾아 사용하려고 시도합니다. 이는 이전에 로그인한 경우 일반적으로 발생하는 동작입니다. 로그인에 대한 자세한 내용은 [인증 가이드](https://huggingface.co/docs/huggingface_hub/quick-start#authentication)를 참조하세요.

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

**프로바이더 직접 액세스**: 자체 API 키를 사용하여 프로바이더의 서비스에 직접 상호작용합니다:
```python
>>> client = InferenceClient(
    provider="replicate",
    api_key="r8_****"  # Your Replicate API key
)
```

자세한 내용은 [Inference Providers 가격 문서](https://huggingface.co/docs/inference-providers/pricing#routed-requests-vs-direct-calls)를 참조하세요.

## 지원되는 제공자 및 작업

[InferenceClient](/docs/huggingface_hub/v2.5.0/ko/package_reference/inference_client#huggingface_hub.InferenceClient)의 목표는 모든 프로바이더에서 Hugging Face 모델로 추론을 실행할 수 있는 가장 간단한 인터페이스를 제공하는 것입니다. 가장 일반적인 작업을 지원하는 간단한 API를 갖추고 있습니다.

Hugging Face 토큰을 사용하면 [chat_completion()](/docs/huggingface_hub/v2.5.0/ko/package_reference/inference_client#huggingface_hub.InferenceClient.chat_completion)은 `https://router.huggingface.co/v1/chat/completions`의 Hugging Face 라우터를 통해 요청을 전달합니다. 추론은 [OpenRouter](https://openrouter.ai)에 의해 처리되며, 해당 모델을 서빙하는 제공자를 선택하고 실패 시 다른 제공자로 재시도합니다. `provider`를 전달하면 해당 제공자로 고정됩니다. 제공자 API 키를 사용하면 해당 제공자를 직접 호출합니다. 특정 모델을 서빙하는 제공자 목록을 확인하려면 Hub의 해당 모델 페이지를 참조하세요.

각 태스크를 지원하는 프로바이더에 대해서는 [Inference Providers 문서](https://huggingface.co/docs/inference-providers/index)를 확인하세요.

> [!TIP]
> 각 작업에 대해 자세히 알아보려면 [Tasks](https://huggingface.co/tasks) 페이지를 확인하세요.

## OpenAI 호환성

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

```diff
- 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 모델 중 아무거나 선택할 수 있습니다. 지원되는 모델 목록은 [여기](https://huggingface.co/models?pipeline_tag=text-generation&other=conversational,text-generation-inference&sort=trending)에서 확인하세요. 인증을 위해 유효한 [User Access Token](https://huggingface.co/settings/tokens)을 `api_key`로 전달하거나 `huggingface_hub`를 사용하여 인증해야 합니다([인증 가이드](https://huggingface.co/docs/huggingface_hub/quick-start#authentication) 참고).

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

```diff
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](/docs/huggingface_hub/v2.5.0/ko/package_reference/inference_client#huggingface_hub.InferenceClient)를 OpenAI의 클라이언트 대신 사용하는 이유는 무엇일까요? 몇 가지 이유가 있습니다:
1. [InferenceClient](/docs/huggingface_hub/v2.5.0/ko/package_reference/inference_client#huggingface_hub.InferenceClient)는 Hugging Face 서비스에 맞게 구성됩니다. Inference Providers로 모델을 실행하려면 `base_url`을 제공할 필요가 없습니다. 또한, 머신이 이미 올바르게 로그인되어 있다면 `token` 또는 `api_key`를 제공할 필요가 없습니다.
2. [InferenceClient](/docs/huggingface_hub/v2.5.0/ko/package_reference/inference_client#huggingface_hub.InferenceClient)는 Text-Generation-Inference(TGI)와 `transformers` 프레임워크 모두에 최적화되어 있어, 항상 최신 업데이트와 동일한 수준을 유지할 수 있습니다.
3. [InferenceClient](/docs/huggingface_hub/v2.5.0/ko/package_reference/inference_client#huggingface_hub.InferenceClient)는 Inference Endpoints 서비스와 통합되어 Inference Endpoint를 시작하고, 상태를 확인하며, 해당 Endpoint에서 추론을 실행하는 과정을 더 쉽게 만들어 줍니다. 자세한 내용은 [Inference Endpoints](./inference_endpoints) 가이드를 참고하세요.

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

## Function Calling

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

```python
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()

response = client.chat.completions.create(
    model="deepseek-ai/DeepSeek-V4.1-Flash",
    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)

```

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

## 구조화된 출력 & JSON 모드

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

JSON 모드와 Structured Outputs 모두 OpenAI API 스펙을 따릅니다. `response_format` 인수를 통해 활성화할 수 있습니다. Structured Outputs의 예시는 다음과 같습니다:

```python
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()

completion = client.chat.completions.create(
    model="deepseek-ai/DeepSeek-V4.1-Flash",
    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)
```
> [!TIP]
> Structured Outputs 및 JSON Mode에서 해당 프로바이더가 지원하는 모델이 무엇인지 확인하려면 프로바이더의 문서를 참조하세요.

## 비동기 클라이언트

`asyncio`와 `httpx2`를 기반으로 한 클라이언트의 비동기 버전도 제공됩니다. 모든 비동기 API 엔드포인트는 [AsyncInferenceClient](/docs/huggingface_hub/v2.5.0/ko/package_reference/inference_client#huggingface_hub.AsyncInferenceClient)를 통해 사용할 수 있습니다. 초기화 및 API는 동기 전용 버전과 완전히 동일합니다.

```py
# 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` 모듈에 대한 자세한 내용은 [공식 문서](https://docs.python.org/3/library/asyncio.html)를 참고하세요.

## MCP 클라이언트

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

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

다음 예시에서는 [OpenRouter](https://openrouter.ai)를 기반으로 하는 [deepseek-ai/DeepSeek-V4.1-Flash](https://huggingface.co/deepseek-ai/DeepSeek-V4.1-Flash) 모델을 사용합니다. 이어서 원격 MCP 서버를 추가하는데, 이 경우 Flux 이미지 생성 도구를 LLM에 사용할 수 있게 해 주는 SSE 서버입니다.

```python
import os

from huggingface_hub import ChatCompletionInputMessage, ChatCompletionStreamOutput, MCPClient

async def main():
    async with MCPClient(
        model="deepseek-ai/DeepSeek-V4.1-Flash",
        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](/docs/huggingface_hub/v2.5.0/ko/package_reference/mcp#huggingface_hub.Agent) 클래스를 제공합니다. 이 'Tiny Agent'는 채팅 루프와 상태를 관리하여 대화형 Agent 생성을 단순화하며, 기본적으로 [MCPClient](/docs/huggingface_hub/v2.5.0/ko/package_reference/mcp#huggingface_hub.MCPClient)를 감싸는 래퍼 역할을 합니다. [MCPClient](/docs/huggingface_hub/v2.5.0/ko/package_reference/mcp#huggingface_hub.MCPClient) 바로 위에 구축된 단순한 while 루프가 되도록 설계되었습니다. 이러한 Agent는 명령줄에서 직접 실행할 수 있습니다:

```bash
# 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](/docs/huggingface_hub/v2.5.0/ko/package_reference/inference_client#huggingface_hub.InferenceClient)의 주요 측면을 살펴보았습니다. 이제 좀 더 고급 팁을 자세히 살펴보겠습니다.

### 청구

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

```py
>>> 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](/docs/huggingface_hub/v2.5.0/ko/package_reference/inference_client#huggingface_hub.InferenceClient)는 inference가 완료될 때까지 "무한정" 대기합니다. 워크플로우에서 더 세밀한 제어가 필요하면 `timeout` 매개변수를 초 단위의 특정 값으로 설정할 수 있습니다. timeout 지연 시간이 지나면 [InferenceTimeoutError](/docs/huggingface_hub/v2.5.0/ko/package_reference/inference_client#huggingface_hub.InferenceTimeoutError)가 발생하며, 이를 코드에서 catch할 수 있습니다:

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

### 바이너리 입력

일부 작업은 바이너리 입력을 요구합니다. 예를 들어 이미지나 오디오 파일을 다룰 때입니다. 이 경우 [InferenceClient](/docs/huggingface_hub/v2.5.0/ko/package_reference/inference_client#huggingface_hub.InferenceClient)는 가능한 한 관대하게 동작하여 다양한 유형을 수용합니다:
- `bytes`의 원시
- 바이너리로 열린 파일 유사 객체(`with open("audio.flac", "rb") as f: ...`)
- 로컬 파일을 가리키는 경로(`str` 또는 `Path`)
- 원격 파일(예: `https://...`)을 가리키는 URL(`str`). 이 경우 파일은
API로 전송됩니다.

```py
>>> 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'}, ...]
```

