Menu
CoddyTech

使用枚举进行分类

本课属于 Coddy AI Engineering 学习旅程的“在代码中调用模型”单元。第 14 课,共 22 课。

文本分类意味着从固定列表中选择一个标签:客服消息的主题、评价的情感、邮件是否为垃圾邮件。自由文本回答可以是 Shipping.、delivery 或一整个句子,而代码无法可靠地对它们进行统计。

schema 中的 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。由于标签始终是列出的字符串之一,你可以将其用作字典键来统计标签,或将消息路由给正确的团队。对于不符合任何标签的文本,可以添加一个像 other 这样的兜底值。

challenge icon

挑战

中等

按主题对支持消息进行分类。初始代码会读取消息的数量,然后读取各条消息,并定义了 TOPICS 以及带有 topic 枚举的 SCHEMA。

  1. 单独发送每条消息,使用 model="claude-opus-5-5"、max_tokens=100,并将 SCHEMA 用作 JSON schema 格式。
  2. 从解析后的 JSON 中读取主题,并打印 <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 在线编译器