0Pricing
AI Prompt Engineering · 课时

将 LLM 用作文本分类器

使用提示进行情感、意图、主题和多标签分类

将 LLM 用作文本分类器 是 CoddyKit 上的免费 AI Prompt Engineering 课时。 这是第 3 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 AI Prompt Engineering 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 AI Prompt Engineering 课程共包含 4 节课。

将 LLM 用作文本分类器

传统文本分类需要带标签的训练数据、模型微调和部署基础设施。LLM 仅凭提示词即可对文本进行分类,无需训练数据。

基于 LLM 的分类器在以下情况下表现出色:

  • 类别需要语义理解(而不仅是关键词匹配)
  • 需要添加新类别而无需重新训练
  • 带标签的示例数量有限
  • 类别较为细微复杂(消息背后的意图,而不仅是主题)

情感分类

情感分类是最常见的分类任务之一。精心设计的提示词在复杂细微的情况下优于简单的关键词匹配:

import anthropic, json

client = anthropic.Anthropic(api_key='YOUR_API_KEY')

def classify_sentiment(text):
    prompt = f'''
Classify the sentiment of the text below.
Return ONLY JSON: {{"sentiment": "positive|negative|neutral", "confidence": "high|medium|low"}}

Definitions:
- positive: Overall favorable opinion or emotion
- negative: Overall unfavorable opinion or dissatisfaction
- neutral: Factual, balanced, or no clear sentiment

Text: {text}
'''
    r = client.messages.create(
        model='claude-opus-4-5', max_tokens=50,
        messages=[{'role': 'user', 'content': prompt}]
    )
    return json.loads(r.content[0].text)

print(classify_sentiment('The product works but setup was painful.'))
print(classify_sentiment('Delivery was incredibly fast and packaging was perfect!'))

意图分类

意图分类用于识别用户想要执行的操作——这对聊天机器人、支持系统和搜索应用至关重要:

INTENT_CATEGORIES = [
    'purchase_intent: User wants to buy or is ready to purchase',
    'complaint: User is dissatisfied and reporting a problem',
    'question: User is asking for information or help',
    'cancellation: User wants to cancel a service or subscription',
    'compliment: User is expressing satisfaction or praise',
    'other: Does not fit any category above'
]

def classify_intent(message):
    categories_str = '\n'.join(f'- {c}' for c in INTENT_CATEGORIES)
    prompt = f'''
Classify the intent of this customer message.
Return JSON: {{"intent": str, "confidence": "high|medium|low"}}

Categories:
{categories_str}

Message: {message}
'''
    r = client.messages.create(model='claude-opus-4-5', max_tokens=80, messages=[{'role': 'user', 'content': prompt}])
    return json.loads(r.content[0].text)

print(classify_intent('I love the app but I need to cancel my plan.'))
print(classify_intent('How do I export my data to CSV?'))

主题分类

主题分类会为文本分配一个主题类别,可用于路由内容、筛选信息流以及对支持工单进行分类:

def classify_topic(article_text, topics):
    topic_list = ', '.join(topics)
    prompt = f'''
Classify the topic of this article. Choose EXACTLY ONE from the list.
Return JSON: {{"topic": str, "secondary_topic": str or null}}

Available topics: {topic_list}

Article (first 300 chars): {article_text[:300]}
'''
    r = client.messages.create(model='claude-opus-4-5', max_tokens=80, messages=[{'role': 'user', 'content': prompt}])
    return json.loads(r.content[0].text)

topics = ['technology', 'sports', 'politics', 'business', 'science', 'health', 'entertainment']
text = 'The FDA approved a new mRNA vaccine for seasonal influenza, marking a breakthrough in vaccine technology.'
result = classify_topic(text, topics)
print(result)

紧急程度分类

紧急程度分类有助于确定支持工单、电子邮件和事件的优先级。精确定义紧急程度级别至关重要:

URGENCY_PROMPT = '''
Classify the urgency of this support ticket.
Return JSON: {{"urgency": str, "reason": str}}

Urgency levels:
- critical: Service is completely down, data loss occurring, or security breach
- high: Major functionality broken, many users affected, no workaround
- medium: Non-critical feature broken, workaround exists, single user affected
- low: Cosmetic issue, enhancement request, general question

Be conservative: only use critical if the ticket explicitly describes a system-wide outage or data loss.

Ticket: {ticket}
'''

def classify_urgency(ticket_text):
    prompt = URGENCY_PROMPT.replace('{ticket}', ticket_text)
    r = client.messages.create(model='claude-opus-4-5', max_tokens=100, messages=[{'role': 'user', 'content': prompt}])
    return json.loads(r.content[0].text)

print(classify_urgency('The entire production database is down. All customers affected.'))
print(classify_urgency('Dark mode button is slightly off-center.'))

多标签分类

有时,一段文本会同时属于多个类别。多标签分类会返回所有适用的类别:

def multi_label_classify(text, labels):
    label_list = ', '.join(labels)
    prompt = f'''
Classify this text. It may belong to multiple categories.
Return JSON: {{"labels": [str], "primary_label": str}}

Available labels: {label_list}

Rules:
- Include all labels that clearly apply
- Do NOT include labels that only marginally apply
- primary_label is the single most relevant label

Text: {text}
'''
    r = client.messages.create(model='claude-opus-4-5', max_tokens=100, messages=[{'role': 'user', 'content': prompt}])
    return json.loads(r.content[0].text)

labels = ['technical', 'billing', 'account', 'bug_report', 'feature_request', 'security']
text = 'I found a bug that exposes other users billing information on my account page.'
print(multi_label_classify(text, labels))

分类提示词模板

一个适用于任意类别集合的可复用分类提示词模板:

def build_classifier(category_definitions, additional_rules=''):
    cats = '\n'.join(f'- {k}: {v}' for k, v in category_definitions.items())
    return f'''
Classify the input text into exactly one category below.
Return JSON: {{"category": str, "confidence": "high|medium|low"}}

Categories:
{cats}
{('\nAdditional rules:\n' + additional_rules) if additional_rules else ''}

Text: {{text}}
'''

language_classifier = build_classifier({
    'formal': 'Business or academic writing, professional context',
    'informal': 'Casual, conversational, slang or colloquial',
    'technical': 'Domain-specific jargon, code, or specialized terminology',
    'emotional': 'High emotional content, personal, expressive'
})

print(language_classifier[:200])

处理有歧义的分类

有些输入确实同时符合多个类别。请设计分类提示词,以明确处理这种歧义:

AMBIGUITY_PROMPT = '''
Classify this customer message. If the message is ambiguous or could fit multiple categories,
choose the category that would be most useful for routing it to the correct team.

Return JSON:
{{
  "category": str,
  "is_ambiguous": true | false,
  "alternative": str or null,
  "reasoning": str
}}

Categories: billing, technical_support, sales, account_management

Message: {message}
'''

message = 'I upgraded my plan but I am still seeing the free tier features.'
r = client.messages.create(
    model='claude-opus-4-5', max_tokens=150,
    messages=[{'role': 'user', 'content': AMBIGUITY_PROMPT.format(message=message)}]
)
print(json.loads(r.content[0].text))

用于提高效率的批量分类

逐项分类的成本很高。批量分类会在一次应用程序接口调用中处理多个输入:

def batch_classify(items, categories):
    items_str = '\n'.join(f'{i+1}. {item}' for i, item in enumerate(items))
    cat_str = ', '.join(categories)

    prompt = f'''
Classify each item below. Categories: {cat_str}
Return JSON: {{"results": [{{"id": int, "category": str, "confidence": str}}]}}

Items:
{items_str}
'''
    r = client.messages.create(model='claude-opus-4-5', max_tokens=300, messages=[{'role': 'user', 'content': prompt}])
    return json.loads(r.content[0].text)['results']

texts = [
    'Absolutely love this product!',
    'It crashed twice today.',
    'What is your refund policy?',
    'The color options are limited.'
]
results = batch_classify(texts, ['positive_feedback', 'bug_report', 'inquiry', 'feature_request'])
for r in results:
    print(f'{texts[r["id"]-1][:30]}... -> {r["category"]} ({r["confidence"]})')

评估分类器准确率

LLM 分类器需要针对已标注示例进行系统评估。请构建一个小型测试集并测量准确率:

labeled_test_set = [
    {'text': 'Great product, no issues!', 'expected': 'positive'},
    {'text': 'The app keeps crashing on startup.', 'expected': 'negative'},
    {'text': 'The screen resolution is 1080p.', 'expected': 'neutral'},
    {'text': 'Worst experience of my life.', 'expected': 'negative'},
    {'text': 'Works as advertised, decent value.', 'expected': 'positive'},
]

def evaluate_classifier(test_set, classify_fn):
    correct = 0
    for example in test_set:
        result = classify_fn(example['text'])
        if result['sentiment'] == example['expected']:
            correct += 1
        else:
            print(f'WRONG: "{example["text"][:40]}" -> got {result["sentiment"]}, expected {example["expected"]}')
    accuracy = correct / len(test_set)
    print(f'Accuracy: {correct}/{len(test_set)} = {accuracy:.0%}')
    return accuracy

evaluate_classifier(labeled_test_set, classify_sentiment)

分类提示词中的少样本示例

在分类提示词中加入少样本示例,可以提高模型处理边界情况和细微类别的准确率。请放置 2-3 个示例,展示相似类别之间的区别:

few_shot_classifier = '''
Classify each customer message as: billing, technical, or general.

Examples:
  Input: "I was charged twice for this month." -> billing
  Input: "The app crashes when I open the dashboard." -> technical
  Input: "Do you have a mobile app?" -> general
  Input: "My invoice shows the wrong plan." -> billing
  Input: "I cannot log in, I get error 403." -> technical

Now classify:
Input: {message}
Return JSON: {"category": str, "confidence": "high|medium|low"}
'''

message = "My subscription was renewed but I cancelled last week."
prompt = few_shot_classifier.replace("{message}", message)
print(prompt)

快速检查

与传统的训练分类器相比,使用 LLM 进行文本分类的主要优势是什么?

LLM 作为分类器——要点总结

基于 LLM 的分类功能强大、灵活且部署迅速:

  • 使用描述而不只是名称来定义类别,以正确处理细微差异的情况
  • 为每次分类返回包含类别和置信度的 JSON
  • 常见模式包括:情感(积极/消极/中性)、意图、主题和紧急程度
  • 多标签分类会返回所有适用的类别以及一个主要标签
  • 批量分类会在一次应用程序接口调用中处理多个输入,从而提高效率
  • 明确处理有歧义的输入——请求返回主要类别、备选类别及推理过程
  • 在部署到生产环境之前,针对已标注测试集评估准确率

常见问题解答

「将 LLM 用作文本分类器」课时是免费的吗?

是的 — 「将 LLM 用作文本分类器」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 AI Prompt Engineering 课程的其余内容,请升级到 CoddyKit PRO。 AI Prompt Engineering 课程共包含 4 节课。

「将 LLM 用作文本分类器」这节课中我会学到什么?

使用提示进行情感、意图、主题和多标签分类 你通过在浏览器中直接运行的动手代码来练习 AI Prompt Engineering,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 AI Prompt Engineering 需要有经验吗?

无需任何先前经验。CoddyKit 上的 AI Prompt Engineering 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 4 节。

「将 LLM 用作文本分类器」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 AI Prompt Engineering 课中编写并运行代码吗?

能。每节 AI Prompt Engineering 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 命名实体提取提示
  2. 由模式驱动的数据提取
  3. 将 LLM 用作文本分类器
  4. 分类中的置信度与不确定性
← 返回 AI Prompt Engineering