TGI Messages API — OpenAI 호환 채팅 API

TGI Messages API — OpenAI 호환 채팅 API

TGI는 OpenAI Chat Completion API와 완전히 호환되는 Messages API 를 지원해요. 이 기능은 버전 1.4.0 이상 에서 사용 가능합니다. OpenAI 클라이언트 라이브러리나 OpenAI 스키마를 기대하는 서드파티 라이브러리를 그대로 사용할 수 있어요.

출처: https://huggingface.co/docs/text-generation-inference/en/messages_api

curl로 요청하기

curl localhost:3000/v1/chat/completions \
  -X POST \
  -d '{
    "model": "tgi",
    "messages": [
      { "role": "system", "content": "You are a helpful assistant." },
      { "role": "user", "content": "What is deep learning?" }
    ],
    "stream": true,
    "max_tokens": 20
  }' \
  -H 'Content-Type: application/json'

스트리밍 요청 (Python)

OpenAI 파이썬 클라이언트를 base_url만 TGI로 바꿔 쓸 수 있어요.

from openai import OpenAI

# init the client but point it to TGI
client = OpenAI(base_url="http://localhost:3000/v1", api_key="-")

chat_completion = client.chat.completions.create(
    model="tgi",
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "What is deep learning?"}
    ],
    stream=True
)

# iterate and print stream
for message in chat_completion:
    print(message)

동기 요청

stream=False로 하면 동기 응답을 받을 수 있어요.

from openai import OpenAI

client = OpenAI(base_url="http://localhost:3000/v1", api_key="-")

chat_completion = client.chat.completions.create(
    model="tgi",
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "What is deep learning?"}
    ],
    stream=False
)
print(chat_completion)

Hugging Face Inference Endpoints

"Text Generation Inference"를 쓰고 채팅 템플릿이 있는 모든 LLM 엔드포인트에서 Messages API를 쓸 수 있어요. base_url에 엔드포인트 URL 뒤 v1/을 포함하고, api_key는 Hugging Face API 키로 바꾸세요.

from openai import OpenAI

client = OpenAI(
    # replace with your endpoint url, make sure to include "v1/" at the end
    base_url="https://vlzz10eq3fol3429.us-east-1.aws.endpoints.huggingface.cloud/v1/",
    # replace with your API key
    api_key="hf_XXX"
)

chat_completion = client.chat.completions.create(
    model="tgi",
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "What is deep learning?"}
    ],
    stream=True
)

for message in chat_completion:
    print(message.choices[0].delta.content, end="")

Amazon SageMaker

SageMaker에서 Messages API를 켜려면 환경 변수 MESSAGES_API_ENABLED=true 를 설정하세요. 그러면 /invocations 라우트가 role과 content로 이루어진 Messages 딕셔너리를 받게 됩니다.

import json
import sagemaker
import boto3
from sagemaker.huggingface import HuggingFaceModel, get_huggingface_llm_image_uri

try:
    role = sagemaker.get_execution_role()
except ValueError:
    iam = boto3.client('iam')
    role = iam.get_role(RoleName='sagemaker_execution_role')['Role']['Arn']

# Hub Model configuration. https://huggingface.co/models
hub = {
    'HF_MODEL_ID': 'HuggingFaceH4/zephyr-7b-beta',
    'SM_NUM_GPUS': json.dumps(1),
    'MESSAGES_API_ENABLED': True
}

# create Hugging Face Model Class
huggingface_model = HuggingFaceModel(
    image_uri=get_huggingface_llm_image_uri("huggingface", version="1.4.0"),
    env=hub,
    role=role,
)

# deploy model to SageMaker Inference
predictor = huggingface_model.deploy(
    initial_instance_count=1,
    instance_type="ml.g5.2xlarge",
    container_startup_health_check_timeout=300,
)

# send request
predictor.predict({
    "messages": [
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "What is deep learning?"}
    ]
})

더 알아보기

  • 빠른 시작은 Quick Tour 참고
  • 지원 모델은 Supported Models 참고
  • Messages API는 TGI 버전 1.4.0 이상에서 지원돼요.