Menu
CoddyTech

Enum으로 분류하기

Coddy AI Engineering 여정의 코드에서 모델 호출하기 섹션에 포함된 레슨. 22개 중 14번째.

텍스트 분류란 정해진 목록에서 하나의 레이블을 선택하는 것을 의미합니다. 예를 들어 고객 지원 메시지의 주제, 리뷰의 감정, 이메일의 스팸 여부 등이 있습니다. 자유 형식의 텍스트 응답은 Shipping., delivery 또는 전체 문장일 수 있으며, 코드로 이러한 응답을 신뢰할 수 있게 집계할 수는 없습니다.

스키마의 enum은 허용되는 값들을 나열하므로, 모델은 반드시 그중 정확히 하나로 답변해야 합니다:

schema = {
    "type": "object",
    "properties": {"mood": {"type": "string", "enum": ["positive", "negative", "neutral"]}},
    "required": ["mood"],
    "additionalProperties": False,
}
response = client.messages.create(
    model="claude-opus-5-5",
    max_tokens=100,
    messages=[{"role": "user", "content": "The soup was cold and the waiter was rude."}],
    output_config={"format": {"type": "json_schema", "schema": schema}},
)
print(json.loads(response.content[0].text)["mood"])

이렇게 하면 negative가 출력됩니다. 레이블은 항상 나열된 문자열 중 하나이므로, 이를 dict 키로 사용해 레이블 개수를 세거나 메시지를 적절한 팀으로 전달할 수 있습니다. 어떤 레이블에도 해당하지 않는 텍스트에 대비해 other와 같은 포괄적인(catch-all) 값을 추가하세요.

challenge icon

챌린지

중급

지원 메시지를 주제별로 분류합니다. 시작 코드는 메시지 개수와 각 메시지를 읽은 다음, topic enum이 있는 TOPICS와 SCHEMA를 정의합니다.

  1. 각 메시지를 개별적으로 보내며, model="claude-opus-5-5", max_tokens=100 및 SCHEMA를 JSON schema 형식으로 설정합니다.
  2. 파싱된 JSON에서 topic을 읽고 <topic>: <message>를 출력합니다.
  3. 마지막 메시지 이후, Counts: 와 모든 주제 및 해당 개수를 TOPICS 순서대로 쉼표와 공백으로 연결하여 출력합니다.

예를 들어, 입력 3, I was charged twice this month., My parcel has not arrived yet., I forgot my password.에 대해 프로그램은 다음을 출력합니다:

billing: I was charged twice this month.
shipping: My parcel has not arrived yet.
account: I forgot my password.
Counts: billing 1, shipping 1, account 1, other 0

직접 해보기

import coddy_ai as anthropic  # 프로덕션 환경: import anthropic
import json

client = anthropic.Anthropic()

TOPICS = ["billing", "shipping", "account", "other"]
SCHEMA = {
    "type": "object",
    "properties": {"topic": {"type": "string", "enum": TOPICS}},
    "required": ["topic"],
    "additionalProperties": False,
}

count = int(input())
messages = [input() for _ in range(count)]

# 모든 메시지에 주제를 라벨링하고, 각 메시지에 대해 "<topic>: <message>"를 출력한 다음,
# TOPICS 순서대로 각 주제의 개수를 출력하세요
quiz icon실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

코드에서 모델 호출하기의 모든 레슨

직접 연습해 보세요: 온라인 Python 컴파일러