AI Agent 的意图识别与工具调用 AI Agent 的一个核心应用场景是自然语言理解 → 意图识别 → 工具调用。这本质上是一个分类问题,即将用户的自然语言输入分类到不同的意图类别,然后路由到相应的工具执行具体任务。
固定 FAQ、按钮选项等不必每次都调大模型:见 Agent Token Routing(本地匹配 → 轻量分类 → 缓存 → LLM)。
工作流程 自然语言理解(NLU)
用户输入:自然语言查询或指令 Agent 使用 LLM 理解语义和上下文 意图识别(Intent Recognition)
LLM 的核心作用:理解自然语言并映射到预定义的意图分类 将用户输入分类到预定义的意图类别 例如:查询天气、预订餐厅、发送邮件、查询数据库等 这是一个多分类任务 参数提取(Slot Filling)
LLM 的第二个作用:从自然语言中提取关键参数供工具使用 从用户输入中提取关键参数 例如:“明天北京的天气” → 时间=明天, 地点=北京 LLM 能理解各种自然语言表达方式并提取结构化参数 工具调用(Tool Calling)
根据识别的意图,调用对应的预开发工具或函数 传递提取的参数给工具 获取工具执行结果 结果组织与返回
将工具返回的结果组织成自然语言 返回给用户 实现示例 # 意图识别与工具调用示例 class IntentBasedAgent: def __init__(self, llm): self.llm = llm self.tools = { "weather": get_weather_tool, "email": send_email_tool, "database": query_database_tool, "calendar": schedule_meeting_tool } async def process(self, user_input: str): # 1. 意图识别(分类) intent_prompt = f""" 分析用户意图,返回意图类别和参数: 用户输入:{user_input} 可选意图:weather, email, database, calendar 返回 JSON 格式:{{"intent": "...", "params": {{...}}}} """ response = await self.llm.query(intent_prompt) intent_data = json.loads(response) intent = intent_data["intent"] params = intent_data["params"] # 2. 根据意图调用相应工具 if intent in self.tools: tool = self.tools[intent] result = await tool(**params) return result else: return "抱歉,我无法理解您的意图" # 使用示例 agent = IntentBasedAgent(llm) # 用户输入:"查询明天北京的天气" # 意图识别结果:intent="weather", params={"date": "明天", "city": "北京"} # 调用工具:get_weather_tool(date="明天", city="北京") 意图识别的实现方式 1. 基于 LLM 的意图识别(推荐) # 使用 Function Calling / Tool Use tools_schema = [ { "name": "get_weather", "description": "查询天气信息", "parameters": { "type": "object", "properties": { "city": {"type": "string", "description": "城市名称"}, "date": {"type": "string", "description": "日期"} } } }, { "name": "send_email", "description": "发送邮件", "parameters": { "type": "object", "properties": { "to": {"type": "string"}, "subject": {"type": "string"}, "body": {"type": "string"} } } } ] # LLM 自动识别意图并返回应调用的工具 response = llm.chat( messages=[{"role": "user", "content": user_input}], tools=tools_schema ) # LLM 返回:tool_call = {"name": "get_weather", "arguments": {"city": "北京", "date": "明天"}} 2. 传统分类模型(轻量级场景) # 使用文本分类模型 from transformers import pipeline classifier = pipeline("text-classification", model="intent-classifier") result = classifier("查询明天北京的天气") # 输出:{"label": "weather", "score": 0.95} 3. 基于规则的意图识别(简单场景) # 关键词匹配 intent_patterns = { "weather": ["天气", "温度", "下雨"], "email": ["发邮件", "发送邮件", "写邮件"], "database": ["查询", "数据", "统计"] } def match_intent(user_input): for intent, keywords in intent_patterns.items(): if any(kw in user_input for kw in keywords): return intent return "unknown" 核心优势 解耦设计
...