HuggingFaceAPIChatGenerator — Hugging Face API 채팅 생성
HuggingFaceAPIChatGenerator — Hugging Face API 채팅 생성
이 생성기(generator)는 다양한 Hugging Face API를 이용해 채팅 완성(chat completion)을 만들 수 있게 해 줘요. Haystack 파이프라인에서 Hugging Face 기반 모델과 대화를 주고받는 한 조각이라고 보시면 돼요.
개요 (Overview)
HuggingFaceAPIChatGenerator는 다양한 Hugging Face API를 이용해 채팅 완성을 생성할 수 있어요.
- Serverless Inference API (Inference Providers) — 무료 티어 제공
- 유료 Inference Endpoints
- 자가 호스팅 Text Generation Inference
이 컴포넌트의 주요 입력은 ChatMessage 객체의 리스트예요. ChatMessage는 메시지와 역할(누가 만들었는지 — user, assistant, system, tool 등), 선택적 메타데이터를 담는 데이터 클래스예요. 문자열을 넘기면 역할이 user인 ChatMessage 하나를 담은 리스트로 변환돼요. 자세한 내용은 ChatMessage 문서를 참고하세요.
컴포넌트는 기본적으로 HF_API_TOKEN 또는 HF_TOKEN 환경 변수를 읽어요. 아니면 초기화할 때 token으로 Hugging Face API 토큰을 직접 넘길 수도 있어요. 아래 코드 예시를 보면 돼요.
토큰이 필요한 경우는 다음과 같아요.
- Serverless Inference API를 사용할 때, 또는
- Inference Endpoints를 사용할 때
스트리밍 (Streaming)
이 Generator는 LLM의 토큰을 출력에 바로 스트리밍하는 스트리밍을 지원해요. streaming_callback 초기화 파라미터에 함수를 넘기면 됩니다.
사용법 (Usage)
HuggingFaceAPIChatGenerator를 쓰려면 huggingface-api-haystack 패키지를 설치해야 해요.
pip install huggingface-api-haystack
단독 사용 (On its own)
Serverless Inference API (Inference Providers) 사용 — 무료 티어 제공
이 API는 Hugging Face Hub에 호스팅된 많은 모델을 빠르게 실험해 볼 수 있게 해 줘요. 추론을 Hugging Face 서버에 맡기는 방식이라, 요청 횟수 제한이 있고 프로덕션용으로는 적합하지 않아요.
이 API를 쓰려면 무료 Hugging Face 토큰이 필요해요.
Generator는 api_params에 model이 있길 기대해요. 성능과 안정성을 위해 provider도 지정하는 걸 권장합니다.
from haystack_integrations.components.generators.huggingface_api import (
HuggingFaceAPIChatGenerator,
)
from haystack.dataclasses import ChatMessage
from haystack.utils import Secret
from haystack_integrations.common.huggingface_api.utils import HFGenerationAPIType
messages = [
ChatMessage.from_system("\\nYou are a helpful, respectful and honest assistant"),
ChatMessage.from_user("What's Natural Language Processing?"),
]
# the api_type can be expressed using the HFGenerationAPIType enum or as a string
api_type = HFGenerationAPIType.SERVERLESS_INFERENCE_API
api_type = "serverless_inference_api" # this is equivalent to the above
generator = HuggingFaceAPIChatGenerator(
api_type=api_type,
api_params={"model": "Qwen/Qwen2.5-7B-Instruct", "provider": "together"},
token=Secret.from_env_var("HF_API_TOKEN"),
)
result = generator.run(messages)
print(result)
유료 Inference Endpoints 사용
이 경우에는 모델의 프라이빗 인스턴스가 Hugging Face에 배포되고, 보통 시간 단위로 비용을 지불해요.
Inference Endpoint를 띄우는 방법은 Hugging Face 문서를 참고하세요.
또한 이 경우에는 Hugging Face 토큰을 제공해야 해요.
Generator는 api_params에 엔드포인트의 url이 있길 기대해요.
from haystack_integrations.components.generators.huggingface_api import (
HuggingFaceAPIChatGenerator,
)
from haystack.dataclasses import ChatMessage
from haystack.utils import Secret
messages = [
ChatMessage.from_system("\\nYou are a helpful, respectful and honest assistant"),
ChatMessage.from_user("What's Natural Language Processing?"),
]
generator = HuggingFaceAPIChatGenerator(
api_type="inference_endpoints",
api_params={"url": "<your-inference-endpoint-url>"},
token=Secret.from_env_var("HF_API_TOKEN"),
)
result = generator.run(messages)
print(result)
Serverless Inference API (Inference Providers)를 텍스트+이미지 입력으로 사용
텍스트와 이미지 입력을 모두 지원하는 멀티모달 모델과도 이 컴포넌트를 함께 쓸 수 있어요.
from haystack_integrations.components.generators.huggingface_api import (
HuggingFaceAPIChatGenerator,
)
from haystack.dataclasses import ChatMessage, ImageContent
from haystack.utils import Secret
from haystack_integrations.common.huggingface_api.utils import HFGenerationAPIType
# Create an image from file path, URL, or base64
image = ImageContent.from_file_path("path/to/your/image.jpg")
# Create a multimodal message with both text and image
messages = [
ChatMessage.from_user(content_parts=["Describe this image in detail", image]),
]
generator = HuggingFaceAPIChatGenerator(
api_type=HFGenerationAPIType.SERVERLESS_INFERENCE_API,
api_params={
"model": "Qwen/Qwen3.5-9B",
"provider": "together",
},
token=Secret.from_token("<your-api-key>"),
)
result = generator.run(messages)
print(result)
자가 호스팅 Text Generation Inference (TGI) 사용
Hugging Face Text Generation Inference는 LLM을 효율적으로 배포하고 서빙하기 위한 툴킷이에요.
가장 최신 버전의 Serverless Inference API와 Inference Endpoints를 구동하는 기술이지만, Docker를 통해 온프레미스에서도 쉽게 쓸 수 있어요.
예를 들어 TGI 컨테이너를 다음과 같이 실행할 수 있어요.
model=HuggingFaceH4/zephyr-7b-beta
volume=$PWD/data # share a volume with the Docker container to avoid downloading weights every run
docker run --gpus all --shm-size 1g -p 8080:80 -v $volume:/data ghcr.io/huggingface/text-generation-inference:1.4 --model-id $model
자세한 내용은 공식 TGI 저장소를 참고하세요.
Generator는 api_params에 TGI 인스턴스의 url이 있길 기대해요.
from haystack_integrations.components.generators.huggingface_api import (
HuggingFaceAPIChatGenerator,
)
from haystack.dataclasses import ChatMessage
messages = [
ChatMessage.from_system("\\nYou are a helpful, respectful and honest assistant"),
ChatMessage.from_user("What's Natural Language Processing?"),
]
generator = HuggingFaceAPIChatGenerator(
api_type="text_generation_inference",
api_params={"url": "http://localhost:8080"},
)
result = generator.run(messages)
print(result)
파이프라인에서 사용 (In a pipeline)
from haystack.components.builders import ChatPromptBuilder
from haystack_integrations.components.generators.huggingface_api import (
HuggingFaceAPIChatGenerator,
)
from haystack.dataclasses import ChatMessage
from haystack import Pipeline
from haystack.utils import Secret
from haystack_integrations.common.huggingface_api.utils import HFGenerationAPIType
# no parameter init, we don't use any runtime template variables
prompt_builder = ChatPromptBuilder()
llm = HuggingFaceAPIChatGenerator(
api_type=HFGenerationAPIType.SERVERLESS_INFERENCE_API,
api_params={"model": "Qwen/Qwen2.5-7B-Instruct", "provider": "together"},
token=Secret.from_env_var("HF_API_TOKEN"),
)
pipe = Pipeline()
pipe.add_component("prompt_builder", prompt_builder)
pipe.add_component("llm", llm)
pipe.connect("prompt_builder.prompt", "llm.messages")
location = "Berlin"
messages = [
ChatMessage.from_system(
"Always respond in German even if some input data is in other languages.",
),
ChatMessage.from_user("Tell me about {{location}}"),
]
result = pipe.run(
data={
"prompt_builder": {
"template_variables": {"location": location},
"template": messages,
},
},
)
print(result)