LLM应用自然语言理解与意图分类深度实战:从规则匹配到LLM语义分类与多标签全解析
【摘要】 LLM应用自然语言理解与意图分类深度实战:从规则匹配到LLM语义分类与多标签全解析 引言意图分类是AI应用理解用户需求的第一步——确定用户想做什么(查询/下单/投诉/闲聊)才能路由到正确的处理流程。传统方法用关键词规则,现代方法用LLM语义分类。本文从意图分类的工程体系讲起,覆盖规则匹配(快速兜底)、LLM语义分类(精准理解)、多标签分类(一个消息多个意图)、意图置信度与歧义处理、上下文意...
LLM应用自然语言理解与意图分类深度实战:从规则匹配到LLM语义分类与多标签全解析
引言
意图分类是AI应用理解用户需求的第一步——确定用户想做什么(查询/下单/投诉/闲聊)才能路由到正确的处理流程。传统方法用关键词规则,现代方法用LLM语义分类。本文从意图分类的工程体系讲起,覆盖规则匹配(快速兜底)、LLM语义分类(精准理解)、多标签分类(一个消息多个意图)、意图置信度与歧义处理、上下文意图修正、意图分类评估、动态意图扩展,构建AI应用NLU工程体系。
一、规则匹配
# nlu/rule_based.py
import re
from dataclasses import dataclass
from typing import Optional
@dataclass
class IntentMatch:
intent: str
confidence: float
matched_rule: str
entities: dict
class RuleBasedClassifier:
"""规则匹配意图分类器"""
RULES = {
"order_query": [
r"(查询|查看|看一下).*(订单|order)",
r"订单.*(状态|进度|到哪)",
r"(我的|那个).*(订单|包裹)",
],
"refund": [
r"(退款|退货|退钱|退掉)",
r"(不要了|取消).*(订单|购买)",
r"(质量|问题).*(退|换)",
],
"product_info": [
r"(介绍|详情|参数|规格).*(产品|商品)",
r"(区别|对比|哪个好)",
r"(多少钱|价格|费用)",
],
"complaint": [
r"(投诉|举报|差评)",
r"(太过分|不接受|不满意)",
r"(经理|主管|负责人)",
],
"greeting": [
r"^(你好|您好|hi|hello|在吗)",
r"(谢谢|感谢|thanks)",
],
}
def classify(self, text: str) -> Optional[IntentMatch]:
"""规则匹配"""
text_lower = text.lower().strip()
for intent, patterns in self.RULES.items():
for pattern in patterns:
if re.search(pattern, text_lower):
return IntentMatch(
intent=intent, confidence=0.8,
matched_rule=pattern,
entities=self._extract_entities(text),
)
return None
def _extract_entities(self, text: str) -> dict:
"""提取实体"""
entities = {}
# 订单号
match = re.search(r'\b(\d{10,20})\b', text)
if match: entities["order_id"] = match.group(1)
# 金额
match = re.search(r'(\d+(?:\.\d+)?)\s*[元块]', text)
if match: entities["amount"] = float(match.group(1))
return entities
二、LLM语义分类
# nlu/llm_classifier.py
class LLMIntentClassifier:
"""LLM语义意图分类"""
CLASSIFY_PROMPT = """对用户消息进行意图分类。
用户消息:{message}
对话历史:{history}
意图类别:
- order_query:查询订单
- refund:退款退货
- product_info:产品咨询
- complaint:投诉
- account:账户问题
- tech_support:技术支持
- greeting:问候闲聊
- other:其他
同时提取实体(订单号/产品名/金额/日期)。
判断置信度(0-1)和紧急度(low/normal/high/urgent)。
输出JSON:
{{"intent": "...", "confidence": 0.0-1.0, "entities": {{}},
"urgency": "...", "reasoning": "..."}}"""
async def classify(self, message: str,
history: list[dict] = None) -> dict:
history_text = "\n".join(
f"{m['role']}: {m['content'][:100]}"
for m in (history or [])[-4:]
)
prompt = self.CLASSIFY_PROMPT.format(
message=message, history=history_text or "(无)",
)
raw = await self.llm.complete(
prompt, response_format={"type": "json_object"},
temperature=0,
)
import json
return json.loads(raw)
三、混合分类器
# nlu/hybrid.py
class HybridIntentClassifier:
"""混合分类器:规则快速兜底+LLM精准理解"""
def __init__(self, llm_client):
self.rule_classifier = RuleBasedClassifier()
self.llm_classifier = LLMIntentClassifier(llm_client)
async def classify(self, message: str,
history: list[dict] = None) -> dict:
# 1. 规则快速匹配(无LLM调用,零延迟)
rule_result = self.rule_classifier.classify(message)
if rule_result and rule_result.confidence >= 0.8:
return {
"intent": rule_result.intent,
"confidence": rule_result.confidence,
"entities": rule_result.entities,
"source": "rule",
"urgency": "normal",
}
# 2. LLM语义分类(规则未命中或低置信度)
llm_result = await self.llm_classifier.classify(message, history)
llm_result["source"] = "llm"
return llm_result
总结
意图分类以"规则-LLM-混合"三层展开:规则匹配以正则模式快速匹配高频意图(零延迟零成本,适合"查询订单"“退款"等模式化表达),LLM语义分类理解非标准表达的意图(“我买的东西还没到”→logistics),混合分类器先尝试规则(80%+置信度直接返回),未命中再调LLM(兼顾速度与精度)。意图分类的工程价值在于:它是AI客服/Agent/路由系统的"第一道闸门”——准确分类意图后才能路由到正确的处理流程(自助/人工/工具调用),错误分类导致用户体验断裂。当意图分类从"关键词if-else"进化为"规则+LLM混合+实体提取+置信度+紧急度"的工程体系,AI应用对用户需求的理解从"猜"变为"懂"。
【声明】本内容来自华为云开发者社区博主,不代表华为云及华为云开发者社区的观点和立场。转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息,否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)