简介
欢迎来到关于 AI 智能体元认知的课程!本章专为那些好奇 AI 智能体如何思考其自身思维过程的初学者而设计。完成本课后,您将理解其中的核心概念,并掌握在 AI 智能体设计中应用元认知的实际案例。
学习目标
完成本课后,您将能够:
- 理解智能体定义中推理循环(reasoning loops)的含义。
- 使用规划和评估技术来帮助构建具备自我纠错能力的智能体。
- 创建您自己的、能够通过操作代码来完成任务的智能体。
元认知简介
元认知(Metacognition)是指涉及“对思考的思考(thinking about thinking)”的高级认知过程。对于 AI 智能体而言,这意味着它们能够基于自我意识和过往经验来评估并调整自己的行为。在代理式 AI(agentic AI)系统的开发中,元认知或“对思考的思考”是一个非常重要的概念。它要求 AI 系统能够意识到自身的内部运作过程,并能据此进行监控、调节和行为适应。这就像我们在审时度势或审视问题时所做的一样。这种自我意识可以帮助 AI 系统做出更好的决策、识别错误并随着时间的推移不断提升性能——这也再次呼应了图灵测试以及关于“AI 是否会接管世界”的辩论。
在代理式 AI 系统的背景下,元认知有助于解决以下几个挑战:
- 透明度 (Transparency): 确保 AI 系统能够解释其推理过程和决策依据。
- 推理 (Reasoning): 增强 AI 系统综合信息并做出合理决策的能力。
- 适应性 (Adaptation): 允许 AI 系统适应新的环境和不断变化的条件。
- 感知 (Perception): 提高 AI 系统在识别和解释环境数据时的准确性。
什么是元认知?
元认知,即“对思考的思考”,是一种涉及对自身认知过程进行自我感知和自我调节的高级认知机制。在 AI 领域,元认知赋予了智能体评估和调整其策略与行动的能力,从而提升其解决问题和决策的水平。通过理解元认知,您可以设计出不仅更智能,而且更具适应性和高效率的 AI 智能体。在真正的元认知中,您会看到 AI 在明确地针对其自身的推理过程进行推理。
- 示例: “我优先考虑了较便宜的航班,因为……但我可能会因此错过直飞航班,让我重新检查一下。” ——这体现了 AI 记录自己选择某条路线的方式和原因。
- 注意到自己犯了错,因为过度依赖了上次的用户偏好,因此它不仅修改了最终的建议,还修改了自身的决策策略。
- 诊断模式,例如:“每当看到用户提到‘太拥挤’时,我不仅应该移除某些景点,还应该反思:如果我总是按照‘受欢迎程度’来排名,那么我挑选‘热门景点’的方法本身就是有缺陷的。”
元认知在 AI 智能体中的重要性
基于以下原因,元认知在 AI 智能体设计中起着至关重要的作用:

- 自我反思 (Self-Reflection): 智能体可以评估自己的表现并找出需要改进的地方。
- 适应性 (Adaptability): 智能体可以根据过往经验和不断变化的环境修改其策略。
- 纠错 (Error Correction): 智能体可以自主检测并纠正错误,从而获得更准确的结果。
- 资源管理 (Resource Management): 智能体可以通过规划和评估自己的行动来优化资源(如时间和计算能力)的使用。
AI 智能体的组成部分
在深入探讨元认知过程之前,有必要先了解 AI 智能体的基本组成部分。一个 AI 智能体通常由以下部分构成:
- 人设/角色 (Persona): 智能体的个性和特征,决定了它与用户互动的方式。
- 工具 (Tools): 智能体可以执行的功能和能力。
- 技能 (Skills): 智能体拥有的知识和专业储备。
这些组件协同工作,构成了一个可以执行特定任务的“专家单元”。
- 示例: 想象一个旅行智能体(travel agent)服务,它不仅能为您规划假期,还能根据实时数据和过往客户的旅行体验来调整规划路线。
示例:旅行智能体服务中的元认知
假设您正在设计一个由 AI 驱动的旅行智能体服务。这个名为“Travel Agent”的智能体负责协助用户规划假期。为了融入元认知,Travel Agent 需要根据自我意识和过往经验来评估和调整自身行为。以下是元认知发挥作用的机制:
当前任务
当前任务是帮助用户规划一趟巴黎之旅。
完成任务的步骤
- 收集用户偏好: 询问用户的旅行日期、预算、兴趣(如博物馆、美食、购物)以及任何具体要求。
- 检索信息: 搜索符合用户偏好的航班选项、住宿、景点和餐厅。
- 生成建议: 提供一份个性化的行程表,包括航班详情、酒店预订和建议活动。
- 基于反馈调整: 询问用户对建议的反馈意见,并进行必要的调整。
所需资源
- 访问航班和酒店预订数据库的权限。
- 巴黎景点和餐厅的信息。
- 先前交互中的用户反馈数据。
经验与自我反思
Travel Agent 利用元认知来评估自身表现并从过往经验中学习。例如:
- 分析用户反馈: Travel Agent 会审查用户反馈,以确定哪些建议受好评,哪些不受欢迎,并据此调整未来的建议。
- 适应性: 如果用户之前提到过不喜欢拥挤的地方,Travel Agent 将来在推荐时就会避开高峰时段的热门旅游景点。
- 纠错: 如果 Travel Agent 在过去的预订中犯过错,例如推荐了一家已经客满的酒店,它就会学会在提出建议前更严格地检查客房可用性。
开发人员实战示例
以下是一个简化的代码示例,展示了 Travel Agent 在融入元认知时的代码逻辑:
Python
class Travel_Agent:
def __init__(self):
self.user_preferences = {}
self.experience_data = []
def gather_preferences(self, preferences):
self.user_preferences = preferences
def retrieve_information(self):
# Search for flights, hotels, and attractions based on preferences
flights = search_flights(self.user_preferences)
hotels = search_hotels(self.user_preferences)
attractions = search_attractions(self.user_preferences)
return flights, hotels, attractions
def generate_recommendations(self):
flights, hotels, attractions = self.retrieve_information()
itinerary = create_itinerary(flights, hotels, attractions)
return itinerary
def adjust_based_on_feedback(self, feedback):
self.experience_data.append(feedback)
# Analyze feedback and adjust future recommendations
self.user_preferences = adjust_preferences(self.user_preferences, feedback)
# Example usage
travel_agent = Travel_Agent()
preferences = {
"destination": "Paris",
"dates": "2025-04-01 to 2025-04-10",
"budget": "moderate",
"interests": ["museums", "cuisine"]
}
travel_agent.gather_preferences(preferences)
itinerary = travel_agent.generate_recommendations()
print("Suggested Itinerary:", itinerary)
feedback = {"liked": ["Louvre Museum"], "disliked": ["Eiffel Tower (too crowded)"]}
travel_agent.adjust_based_on_feedback(feedback)
为什么元认知很重要
- 自我反思: 智能体可以分析自身的表现并找出改进空间。
- 适应性: 智能体可以根据反馈和不断变化的条件修改策略。
- 纠错: 智能体可以自主发现并纠正错误。
- 资源管理: 智能体可以优化资源消耗,如时间和计算能力。
通过融入元认知,Travel Agent 可以提供更具个性化、更准确的旅行建议,从而显著提升整体用户体验。
2. 智能体中的规划 (Planning in Agents)
规划是 AI 智能体行为中至关重要的组成部分。它涉及勾勒出实现目标所需的步骤,同时综合考虑当前状态、可用资源以及潜在的障碍。
规划的要素
- 当前任务: 清晰地定义任务。
- 完成任务的步骤: 将任务拆解为可管理的多个步骤。
- 所需资源: 确定执行所需的资源。
- 经验: 利用过往经验为规划提供指导。
示例: 以下是 Travel Agent 协助用户有效规划旅行需要执行的具体步骤:
Travel Agent 的执行步骤
收集用户偏好
- 询问用户关于旅行日期、预算、兴趣以及任何特定要求的详情。
- 示例:“您计划什么时候去旅行?”“您的预算范围是多少?”“您在度假时喜欢什么活动?”
检索信息
- 根据用户偏好搜索相关的旅行选项。
- 航班:寻找在用户预算和预定旅行日期内的可用航班。
- 住宿:寻找符合用户在位置、价格和设施方面偏好的酒店或租赁物业。
- 景点和餐厅:找出与用户兴趣相符的热门景点、活动和餐饮选项。
生成建议
- 将检索到的信息汇总成一份个性化的行程表。
- 提供航班选项、酒店预订和建议活动等详情,确保这些建议是为用户量身定制的。
向用户展示行程表
- 将拟定的行程表分享给用户进行审查。
- 示例:“这是为您前往巴黎建议的行程表。里面包含了航班详情、酒店预订以及推荐的活动和餐厅列表。请告诉我您的想法!”
收集反馈
- 询问用户对拟定行程的反馈。
- 示例:“您喜欢这些航班选项吗?”“这家酒店符合您的需求吗?”“有任何您想添加或删除的活动吗?”
基于反馈进行调整
- 根据用户的反馈修改行程。
- 对航班、住宿和活动建议进行必要的更改,以更好地匹配用户的偏好。
最终确认
- 向用户提交更新后的行程表以供最终确认。
- 示例:“我已经根据您的反馈做出了调整。这是更新后的行程表,您看可以吗?”
预订并确认
- 一旦用户批准行程,就继续预订航班、住宿和任何预先计划的活动。
- 将确认详情发送给用户。
提供持续支持
- 随时准备好在用户旅行前和旅行期间协助他们处理任何更改或额外请求。
- 示例:“如果您在旅行期间需要任何进一步的帮助,请随时联系我!”
交互示例
Python
class Travel_Agent:
def __init__(self):
self.user_preferences = {}
self.experience_data = []
def gather_preferences(self, preferences):
self.user_preferences = preferences
def retrieve_information(self):
flights = search_flights(self.user_preferences)
hotels = search_hotels(self.user_preferences)
attractions = search_attractions(self.user_preferences)
return flights, hotels, attractions
def generate_recommendations(self):
flights, hotels, attractions = self.retrieve_information()
itinerary = create_itinerary(flights, hotels, attractions)
return itinerary
def adjust_based_on_feedback(self, feedback):
self.experience_data.append(feedback)
self.user_preferences = adjust_preferences(self.user_preferences, feedback)
# Example usage within a booing request
travel_agent = Travel_Agent()
preferences = {
"destination": "Paris",
"dates": "2025-04-01 to 2025-04-10",
"budget": "moderate",
"interests": ["museums", "cuisine"]
}
travel_agent.gather_preferences(preferences)
itinerary = travel_agent.generate_recommendations()
print("Suggested Itinerary:", itinerary)
feedback = {"liked": ["Louvre Museum"], "disliked": ["Eiffel Tower (too crowded)"]}
travel_agent.adjust_based_on_feedback(feedback)
3. 纠错式 RAG 系统 (Corrective RAG System)
首先,让我们从理解 RAG 工具 (RAG Tool) 和 预先上下文加载 (Pre-emptive Context Load) 之间的区别开始。

检索增强生成 (RAG)
RAG 结合了检索系统和生成模型。当发起查询时,检索系统会从外部数据源获取相关的文档或数据,这些检索到的信息随后被用于增强生成模型的输入。这有助于模型生成更准确、更符合上下文语境的响应。在 RAG 系统中,智能体从知识库中检索相关信息,并利用这些信息来生成适当的响应或采取行动。
纠错式 RAG 方法 (Corrective RAG Approach)
纠错式 RAG 方法侧重于利用 RAG 技术来纠正错误并提高 AI 智能体的准确性。这包括:
- 提示技术 (Prompting Technique): 使用特定的提示词来引导智能体检索相关信息。
- 工具 (Tool): 实施相关算法和机制,使智能体能够评估检索信息的关联度并生成准确的回答。
- 评估 (Evaluation): 持续评估智能体的表现,并进行调整以提高其准确性和效率。
示例:搜索智能体中的纠错式 RAG考虑一个从网络检索信息来回答用户查询的搜索智能体。纠错式 RAG 方法可能包含:
- 提示技术: 基于用户的输入构建搜索查询。
- 工具: 使用自然语言处理和机器学习算法对搜索结果进行排名和过滤。
- 评估: 分析用户反馈,以识别并纠正检索信息中的不准确之处。
Travel Agent 中的纠错式 RAG
纠错式 RAG 提升了 AI 检索和生成信息的能力,同时能纠正任何不准确之处。让我们看看 Travel Agent 如何利用纠错式 RAG 方法提供更精准、相关的旅行建议。
这涉及:
- 提示技术: 使用特定提示引导智能体检索相关信息。
- 工具: 实施算法和机制,使智能体能评估所检索信息的关联度并生成准确回应。
- 评估: 持续评估智能体的表现,并做出调整以提升准确性和效率。
在 Travel Agent 中实施纠错式 RAG 的步骤:
1, 初始用户交互Travel Agent 收集用户的初始偏好,如目的地、旅行日期、预算和兴趣。
Python
preferences = {
"destination": "Paris",
"dates": "2025-04-01 to 2025-04-10",
"budget": "moderate",
"interests": ["museums", "cuisine"]
}
2, 信息检索
Travel Agent 根据用户偏好检索有关航班、住宿、景点和餐厅的信息。
Python
flights = search_flights(preferences)
hotels = search_hotels(preferences)
attractions = search_attractions(preferences)
3, 生成初始建议
Travel Agent 使用检索到的信息生成个性化的行程表。
Python
itinerary = create_itinerary(flights, hotels, attractions)
print("Suggested Itinerary:", itinerary)
4, 收集用户反馈
Travel Agent 询问用户对初始建议的反馈。
Python
feedback = {
"liked": ["Louvre Museum"],
"disliked": ["Eiffel Tower (too crowded)"]
}
5, 纠错式 RAG 流程
- 提示技术: Travel Agent 根据用户反馈构建新的搜索查询。
Python
if "disliked" in feedback:
preferences["avoid"] = feedback["disliked"]
- 工具: Travel Agent 使用算法对新的搜索结果进行排名和过滤,基于用户反馈强化关联度。
Python
new_attractions = search_attractions(preferences)
new_itinerary = create_itinerary(flights, hotels, new_attractions)
print("Updated Itinerary:", new_itinerary)
- 评估: Travel Agent 通过分析用户反馈持续评估其建议的相关性和准确性,并做出必要的调整。
Python
def adjust_preferences(preferences, feedback):
if "liked" in feedback:
preferences["favorites"] = feedback["liked"]
if "disliked" in feedback:
preferences["avoid"] = feedback["disliked"]
return preferences
preferences = adjust_preferences(preferences, feedback)
实际示例代码
这是一个包含了纠错式 RAG 方法的 Travel Agent 简化 Python 代码示例:
Python
class Travel_Agent:
def __init__(self):
self.user_preferences = {}
self.experience_data = []
def gather_preferences(self, preferences):
self.user_preferences = preferences
def retrieve_information(self):
flights = search_flights(self.user_preferences)
hotels = search_hotels(self.user_preferences)
attractions = search_attractions(self.user_preferences)
return flights, hotels, attractions
def generate_recommendations(self):
flights, hotels, attractions = self.retrieve_information()
itinerary = create_itinerary(flights, hotels, attractions)
return itinerary
def adjust_based_on_feedback(self, feedback):
self.experience_data.append(feedback)
self.user_preferences = adjust_preferences(self.user_preferences, feedback)
new_itinerary = self.generate_recommendations()
return new_itinerary
# Example usage
travel_agent = Travel_Agent()
preferences = {
"destination": "Paris",
"dates": "2025-04-01 to 2025-04-10",
"budget": "moderate",
"interests": ["museums", "cuisine"]
}
travel_agent.gather_preferences(preferences)
itinerary = travel_agent.generate_recommendations()
print("Suggested Itinerary:", itinerary)
feedback = {"liked": ["Louvre Museum"], "disliked": ["Eiffel Tower (too crowded)"]}
new_itinerary = travel_agent.adjust_based_on_feedback(feedback)
print("Updated Itinerary:", new_itinerary)
预先上下文加载 (Pre-emptive Context Load)
预先上下文加载是指在处理查询之前,将相关的上下文或背景信息预先加载到模型中。这意味着模型从一开始就能访问这些信息,从而帮助它生成更明智的回复,而无需在处理过程中再额外去检索数据。
以下是 Python 中旅行智能体应用预先上下文加载的一个简单示例:
Python
class TravelAgent:
def __init__(self):
# Pre-load popular destinations and their information
self.context = {
"Paris": {"country": "France", "currency": "Euro", "language": "French", "attractions": ["Eiffel Tower", "Louvre Museum"]},
"Tokyo": {"country": "Japan", "currency": "Yen", "language": "Japanese", "attractions": ["Tokyo Tower", "Shibuya Crossing"]},
"New York": {"country": "USA", "currency": "Dollar", "language": "English", "attractions": ["Statue of Liberty", "Times Square"]},
"Sydney": {"country": "Australia", "currency": "Dollar", "language": "English", "attractions": ["Sydney Opera House", "Bondi Beach"]}
}
def get_destination_info(self, destination):
# Fetch destination information from pre-loaded context
info = self.context.get(destination)
if info:
return f"{destination}:\nCountry: {info['country']}\nCurrency: {info['currency']}\nLanguage: {info['language']}\nAttractions: {', '.join(info['attractions'])}"
else:
return f"Sorry, we don't have information on {destination}."
# Example usage
travel_agent = TravelAgent()
print(travel_agent.get_destination_info("Paris"))
print(travel_agent.get_destination_info("Tokyo"))
解析:
- 初始化 (__init__ 方法): TravelAgent 类预先加载了一个包含巴黎、东京、纽约和悉尼等热门目的地信息的字典。该字典包含每个目的地的国家、货币、语言和主要景点等详细信息。
- 检索信息 (get_destination_info 方法): 当用户查询特定目的地时,该方法会从预加载的上下文字典中获取相关信息。
通过预加载上下文,旅行智能体应用可以快速响应用户查询,而无需实时从外部源检索这些信息。这使得应用程序更高效且响应更迅速。
在迭代前以目标进行规划自举 (Bootstrapping the Plan with a Goal Before Iterating)
以目标引导/自举(Bootstrapping)规划,意味着在开始时就先在心中树立一个明确的目标或期望结果。通过提前定义该目标,模型可以在整个迭代过程中将其用作指导原则。这有助于确保每次迭代都更接近实现预期结果,从而使该过程更加高效和聚焦。
以下是在 Python 中如何为旅行智能体实现以目标进行自举规划的示例:
场景旅行智能体希望为客户规划定制假期。目标是制定一份旅行行程表,根据客户的偏好和预算最大化客户的满意度。
步骤
- 明确客户的偏好和预算。
- 根据这些偏好自举生成(Bootstrap)初始计划。
- 迭代完善计划,为提升客户满意度进行优化。
Python
class TravelAgent:
def __init__(self, destinations):
self.destinations = destinations
def bootstrap_plan(self, preferences, budget):
plan = []
total_cost = 0
for destination in self.destinations:
if total_cost + destination['cost'] <= budget and self.match_preferences(destination, preferences):
plan.append(destination)
total_cost += destination['cost']
return plan
def match_preferences(self, destination, preferences):
for key, value in preferences.items():
if destination.get(key) != value:
return False
return True
def iterate_plan(self, plan, preferences, budget):
for i in range(len(plan)):
for destination in self.destinations:
if destination not in plan and self.match_preferences(destination, preferences) and self.calculate_cost(plan, destination) <= budget:
plan[i] = destination
break
return plan
def calculate_cost(self, plan, new_destination):
return sum(destination['cost'] for destination in plan) + new_destination['cost']
# Example usage
destinations = [
{"name": "Paris", "cost": 1000, "activity": "sightseeing"},
{"name": "Tokyo", "cost": 1200, "activity": "shopping"},
{"name": "New York", "cost": 900, "activity": "sightseeing"},
{"name": "Sydney", "cost": 1100, "activity": "beach"},
]
preferences = {"activity": "sightseeing"}
budget = 2000
travel_agent = TravelAgent(destinations)
initial_plan = travel_agent.bootstrap_plan(preferences, budget)
print("Initial Plan:", initial_plan)
refined_plan = travel_agent.iterate_plan(initial_plan, preferences, budget)
print("Refined Plan:", refined_plan)
代码解析:
- 初始化 (__init__ 方法): TravelAgent 实例使用潜在目的地的列表进行初始化,每个目的地都有名称、成本和活动类型等属性。
- 自举规划 (bootstrap_plan 方法): 该方法根据客户的偏好和预算创建一个初始旅行计划。它遍历目的地列表,如果目的地符合客户偏好且在预算范围内,就将其添加到计划中。
- 匹配偏好 (match_preferences 方法): 检查目的地是否与客户偏好匹配。
- 迭代计划 (iterate_plan 方法): 该方法通过尝试用更好的匹配项(考虑偏好和预算约束)来替换计划中的各个目的地,从而完善初始计划。
- 计算成本 (calculate_cost 方法): 该方法计算当前计划加上一个潜在新目的地的总成本。
示例用法:
- 初始计划: 旅行智能体根据客户偏好(观光)和预算($2000)创建初始计划。
- 完善计划: 旅行智能体对计划进行迭代,以针对偏好和预算进行优化。
通过以明确目标(如最大化客户满意度)对计划进行初始自举,并不断迭代完善,旅行智能体便可以为客户创建定制化、最优化的旅行行程。这种方法确保了旅行计划从一开始就符合客户的偏好和预算,并在每次迭代中不断变好。
利用 LLM 进行重新排序和评分 (Taking Advantage of LLM for Re-ranking and Scoring)
大语言模型(LLMs)可通过评估检索文档或生成回答的关联度和质量来进行重新排序(Re-ranking)和评分(Scoring)。其工作原理如下:
- 检索 (Retrieval): 初始检索步骤基于查询获取一组候选文档或回答。
- 重新排序 (Re-ranking): LLM 评估这些候选者,并根据其相关性和质量对其进行重新排名。此步骤确保最相关和最高质量的信息排在最前面。
- 评分 (Scoring): LLM 为每个候选者打分,反映其相关性和质量。这有助于为用户选择最佳的回应或文档。
通过利用 LLMs 进行重新排序和评分,系统可以提供更准确、更符合语境的信息,改善整体用户体验。
以下是一个旅行智能体如何使用大语言模型(LLM)基于用户偏好对旅行目的地进行重新排名和评分的 Python 示例:
场景 - 基于偏好的旅行预订器旅行智能体希望根据客户的偏好向其推荐最佳旅行目的地。LLM 将协助对目的地进行重新排序和评分,确保呈现出最相关的选项。
步骤:
- 收集用户偏好。
- 检索潜在旅游目的地的列表。
- 使用 LLM 根据用户偏好对目的地进行重新排名和评分。
以下是如何将之前的示例更新为使用 Azure OpenAI 服务的代码:
前提条件:
- 您需要拥有一个 Azure 订阅。
- 创建一个 Azure OpenAI 资源并获取您的 API 密钥。
Python
import requests
import json
class TravelAgent:
def __init__(self, destinations):
self.destinations = destinations
def get_recommendations(self, preferences, api_key, endpoint):
# Generate a prompt for the Azure OpenAI
prompt = self.generate_prompt(preferences)
# Define headers and payload for the request
headers = {
'Content-Type': 'application/json',
'Authorization': f'Bearer {api_key}'
}
payload = {
"prompt": prompt,
"max_tokens": 150,
"temperature": 0.7
}
# Call the Azure OpenAI API to get the re-ranked and scored destinations
response = requests.post(endpoint, headers=headers, json=payload)
response_data = response.json()
# Extract and return the recommendations
recommendations = response_data['choices'][0]['text'].strip().split('\n')
return recommendations
def generate_prompt(self, preferences):
prompt = "Here are the travel destinations ranked and scored based on the following user preferences:\n"
for key, value in preferences.items():
prompt += f"{key}: {value}\n"
prompt += "\nDestinations:\n"
for destination in self.destinations:
prompt += f"- {destination['name']}: {destination['description']}\n"
return prompt
# Example usage
destinations = [
{"name": "Paris", "description": "City of lights, known for its art, fashion, and culture."},
{"name": "Tokyo", "description": "Vibrant city, famous for its modernity and traditional temples."},
{"name": "New York", "description": "The city that never sleeps, with iconic landmarks and diverse culture."},
{"name": "Sydney", "description": "Beautiful harbour city, known for its opera house and stunning beaches."},
]
preferences = {"activity": "sightseeing", "culture": "diverse"}
api_key = 'your_azure_openai_api_key'
endpoint = 'https://your-endpoint.com/openai/deployments/your-deployment-name/completions?api-version=2022-12-01'
travel_agent = TravelAgent(destinations)
recommendations = travel_agent.get_recommendations(preferences, api_key, endpoint)
print("Recommended Destinations:")
for rec in recommendations:
print(rec)
代码解析 - 偏好预订器
- 初始化: TravelAgent 实例使用具有名称和描述等属性的潜在目的地列表进行初始化。
- 获取推荐 (get_recommendations 方法): 该方法根据用户偏好为 Azure OpenAI 服务生成提示词,并向 Azure OpenAI API 发起 HTTP POST 请求,以获取重新排名和评分后的目的地。
- 生成提示词 (generate_prompt 方法): 此方法构建了提供给 Azure OpenAI 的提示词,其中包含用户的偏好和目的地列表。该提示词引导模型根据提供的偏好对目的地进行重新排序和打分。
- API 调用: 使用 requests 库向 Azure OpenAI API 端点发出 HTTP POST 请求。响应体包含了重新排名的结果。
- 示例用法: 旅行智能体收集用户偏好(例如,对观光和多元文化感兴趣),并利用 Azure OpenAI 服务获取经过重新排序和打分的旅行目的地推荐。
(注:请确保将 your_azure_openai_api_key 替换为您真实的 API 密钥,并将 https://your-endpoint.com/... 替换为您 Azure OpenAI 部署的真实端点 URL)
通过利用 LLM 进行重新排序和评分,旅行智能体能为客户提供更个性化、更相关的推荐,提升他们的整体体验。
RAG:提示词技术 vs 工具 (RAG: Prompting Technique vs Tool)
在 AI 智能体开发中,检索增强生成 (RAG) 既可以是一种提示技术 (Prompting Technique),也可以是一种工具 (Tool)。理解这两者之间的区别,可以帮助您在项目中更有效地利用 RAG。
RAG 作为一种提示技术 (Prompting Technique)
它是什么?作为一种提示技术,RAG 涉及构思特定的查询或提示词,以引导从大型语料库或数据库中检索相关信息。随后,这些信息将被用于生成响应或行动。
它是如何工作的:
- 制定提示词 (Formulate Prompts): 根据手头的任务或用户输入,创建结构良好的提示词或查询。
- 检索信息 (Retrieve Information): 使用这些提示词从预先存在的知识库或数据集中搜索相关数据。
- 生成响应 (Generate Response): 将检索到的信息与生成式 AI 模型相结合,生成全面、连贯的回应。
旅行智能体示例:
用户输入: “我想去巴黎看博物馆。”
提示词: “寻找巴黎顶级的博物馆。”
检索到的信息: 有关卢浮宫、奥赛博物馆等详情。
生成的响应: “以下是巴黎一些顶级的博物馆:卢浮宫、奥赛博物馆和蓬皮杜中心。”
RAG 作为一种工具 (Tool)
它是什么?
作为一种工具,RAG 表现为一个自动化检索和生成过程的集成系统。这让开发人员能够更轻松地实现复杂的 AI 功能,而无需为每一个查询手动去编写提示词。
它是如何工作的:
- 集成 (Integration): 将 RAG 嵌入到 AI 智能体的架构中,允许其自动处理检索和生成任务。
- 自动化 (Automation): 该工具管理从接收用户输入到生成最终响应的整个流程,而无需在每个步骤都明确使用提示词。
- 效率 (Efficiency): 通过简化检索和生成过程来提升智能体的性能,从而实现更快速、更准确的响应。
旅行智能体 (Travel Agent) 示例:
- 用户输入: “我想去巴黎看博物馆。”
- RAG 工具: 自动检索有关博物馆的信息并生成响应。
- 生成的响应: “以下是巴黎一些顶级的博物馆:卢浮宫、奥赛博物馆和蓬皮杜中心。”
对比 (Comparison)
| 方面 (Aspect) | 提示词技术 (Prompting Technique) | 工具 (Tool) |
| 手动 vs 自动 | 为每个查询手动构建提示词。 | 检索和生成过程自动化。 |
| 控制力 | 对检索过程提供更多控制权。 | 简化并自动执行检索和生成。 |
| 灵活性 | 允许根据特定需求定制提示词。 | 对于大规模实施更为高效。 |
| 复杂性 | 需要精心设计和调整提示词。 | 更容易集成到 AI 智能体的架构中。 |
实用示例 (Practical Examples)
提示词技术示例:
Python
def search_museums_in_paris():
prompt = "Find top museums in Paris"
search_results = search_web(prompt)
return search_results
museums = search_museums_in_paris()
print("Top Museums in Paris:", museums)
工具示例:
Python
class Travel_Agent:
def __init__(self):
self.rag_tool = RAGTool()
def get_museums_in_paris(self):
user_input = "I want to visit museums in Paris."
response = self.rag_tool.retrieve_and_generate(user_input)
return response
travel_agent = Travel_Agent()
museums = travel_agent.get_museums_in_paris()
print("Top Museums in Paris:", museums)
评估相关性 (Evaluating Relevancy)
评估相关性是 AI 智能体性能评估中至关重要的一环。它确保了智能体检索和生成的信息对用户来说是恰当、准确且有用的。让我们来探讨如何在 AI 智能体中评估相关性,包括实用示例和技术。
评估相关性的核心概念
- 上下文感知 (Context Awareness):
智能体必须理解用户查询的上下文,才能检索和生成相关信息。
示例: 如果用户询问“巴黎最好的餐厅”,智能体应考虑用户的偏好,如菜系和预算。
- 准确性 (Accuracy):
智能体提供的信息在事实上必须是正确的且是最新的。
示例: 推荐目前正在营业且评价良好的餐厅,而不是过时或已关闭的选项。
- 用户意图 (User Intent):
智能体应推断用户查询背后的意图,以提供最相关的信息。
示例: 如果用户寻找“经济型酒店”,智能体应优先推荐价格实惠的选项。
- 反馈循环 (Feedback Loop):
持续收集和分析用户反馈,有助于智能体不断完善其相关性评估过程。
示例: 将用户对先前推荐的评分和反馈纳入考量,以改善未来的响应。
评估相关性的实用技巧
- 相关性评分 (Relevance Scoring):
根据检索到的项目与用户查询和偏好的匹配程度,为每个项目分配一个相关性分数。
示例:
Python
def relevance_score(item, query):
score = 0
if item['category'] in query['interests']:
score += 1
if item['price'] <= query['budget']:
score += 1
if item['location'] == query['destination']:
score += 1
return score
- 过滤与排序 (Filtering and Ranking):
过滤掉不相关的项目,并根据相关性分数对剩余项目进行排序。
示例:
Python
def filter_and_rank(items, query):
ranked_items = sorted(items, key=lambda item: relevance_score(item, query), reverse=True)
return ranked_items[:10] # Return top 10 relevant items
- 自然语言处理 (NLP):
利用 NLP 技术理解用户的查询并检索相关信息。
示例:
Python
def process_query(query):
# Use NLP to extract key information from the user's query
processed_query = nlp(query)
return processed_query
- 整合用户反馈 (User Feedback Integration):
收集用户对所提供推荐的反馈,并据此调整未来的相关性评估。
示例:
Python
def adjust_based_on_feedback(feedback, items):
for item in items:
if item['name'] in feedback['liked']:
item['relevance'] += 1
if item['name'] in feedback['disliked']:
item['relevance'] -= 1
return items
示例:Travel Agent 中的相关性评估
以下是 Travel Agent 如何评估旅行建议相关性的实际示例:
Python
class Travel_Agent:
def __init__(self):
self.user_preferences = {}
self.experience_data = []
def gather_preferences(self, preferences):
self.user_preferences = preferences
def retrieve_information(self):
flights = search_flights(self.user_preferences)
hotels = search_hotels(self.user_preferences)
attractions = search_attractions(self.user_preferences)
return flights, hotels, attractions
def generate_recommendations(self):
flights, hotels, attractions = self.retrieve_information()
ranked_hotels = self.filter_and_rank(hotels, self.user_preferences)
itinerary = create_itinerary(flights, ranked_hotels, attractions)
return itinerary
def filter_and_rank(self, items, query):
ranked_items = sorted(items, key=lambda item: self.relevance_score(item, query), reverse=True)
return ranked_items[:10] # Return top 10 relevant items
def relevance_score(self, item, query):
score = 0
if item['category'] in query['interests']:
score += 1
if item['price'] <= query['budget']:
score += 1
if item['location'] == query['destination']:
score += 1
return score
def adjust_based_on_feedback(self, feedback, items):
for item in items:
if item['name'] in feedback['liked']:
item['relevance'] += 1
if item['name'] in feedback['disliked']:
item['relevance'] -= 1
return items
# Example usage
travel_agent = Travel_Agent()
preferences = {
"destination": "Paris",
"dates": "2025-04-01 to 2025-04-10",
"budget": "moderate",
"interests": ["museums", "cuisine"]
}
travel_agent.gather_preferences(preferences)
itinerary = travel_agent.generate_recommendations()
print("Suggested Itinerary:", itinerary)
feedback = {"liked": ["Louvre Museum"], "disliked": ["Eiffel Tower (too crowded)"]}
updated_items = travel_agent.adjust_based_on_feedback(feedback, itinerary['hotels'])
print("Updated Itinerary with Feedback:", updated_items)
意图搜索 (Search with Intent)
意图搜索涉及理解和解释用户查询背后的根本目的或目标,以检索和生成最相关、最有用的信息。这种方法超越了简单的关键词匹配,而是专注于掌握用户的实际需求和上下文。
意图搜索的核心概念
- 理解用户意图 (Understanding User Intent):
用户意图主要可分为三种类型:信息型 (informational)、导航型 (navigational) 和交易型 (transactional)。
- 信息型意图: 用户寻求有关某个主题的信息(例如,“巴黎最好的博物馆是哪些?”)。
- 导航型意图: 用户想要导航到特定的网站或页面(例如,“卢浮宫官方网站”)。
- 交易型意图: 用户旨在执行一项交易,如预订航班或进行购买(例如,“预订去巴黎的航班”)。
- 上下文感知 (Context Awareness):
分析用户查询的上下文有助于准确识别其意图。这包括考虑以前的交互、用户偏好以及当前查询的具体细节。
- 自然语言处理 (NLP):
采用 NLP 技术来理解和解释用户提供的自然语言查询。这包括实体识别、情感分析和查询解析等任务。
- 个性化 (Personalization):
根据用户的历史记录、偏好和反馈对搜索结果进行个性化处理,可提升检索信息的相关性。
实用示例:Travel Agent 中的意图搜索
让我们以 Travel Agent 为例,看看如何实现意图搜索。
收集用户偏好
Python
class Travel_Agent:
def __init__(self):
self.user_preferences = {}
def gather_preferences(self, preferences):
self.user_preferences = preferences
理解用户意图
Python
def identify_intent(query):
if "book" in query or "purchase" in query:
return "transactional"
elif "website" in query or "official" in query:
return "navigational"
else:
return "informational"
上下文感知
Python
def analyze_context(query, user_history):
# Combine current query with user history to understand context
context = {
"current_query": query,
"user_history": user_history
}
return context
搜索并个性化结果
Python
def search_with_intent(query, preferences, user_history):
intent = identify_intent(query)
context = analyze_context(query, user_history)
if intent == "informational":
search_results = search_information(query, preferences)
elif intent == "navigational":
search_results = search_navigation(query)
elif intent == "transactional":
search_results = search_transaction(query, preferences)
personalized_results = personalize_results(search_results, user_history)
return personalized_results
def search_information(query, preferences):
# Example search logic for informational intent
results = search_web(f"best {preferences['interests']} in {preferences['destination']}")
return results
def search_navigation(query):
# Example search logic for navigational intent
results = search_web(query)
return results
def search_transaction(query, preferences):
# Example search logic for transactional intent
results = search_web(f"book {query} to {preferences['destination']}")
return results
def personalize_results(results, user_history):
# Example personalization logic
personalized = [result for result in results if result not in user_history]
return personalized[:10] # Return top 10 personalized results
示例用法
Python
travel_agent = Travel_Agent()
preferences = {
"destination": "Paris",
"interests": ["museums", "cuisine"]
}
travel_agent.gather_preferences(preferences)
user_history = ["Louvre Museum website", "Book flight to Paris"]
query = "best museums in Paris"
results = search_with_intent(query, preferences, user_history)
print("Search Results:", results)
4. 将生成代码作为一种工具 (Generating Code as a Tool)
代码生成智能体使用 AI 模型来编写和执行代码,从而解决复杂问题并自动化执行任务。
代码生成智能体 (Code Generating Agents)
代码生成智能体利用生成式 AI 模型来编写和执行代码。这些智能体可以通过生成并在各种编程语言中运行代码,来解决复杂问题、自动化任务并提供有价值的洞察。
实际应用
- 自动化代码生成: 为特定任务生成代码片段,例如数据分析、网页抓取或机器学习。
- 将 SQL 作为 RAG: 使用 SQL 查询从数据库中检索和操作数据。
- 解决问题: 创建并执行代码以解决特定问题,例如优化算法或分析数据。
示例:用于数据分析的代码生成智能体
假设您正在设计一个代码生成智能体。它的工作流程可能如下:
- 任务: 分析数据集以识别趋势和模式。
- 步骤:
- 将数据集加载到数据分析工具中。
- 生成 SQL 查询以过滤和聚合数据。
- 执行查询并检索结果。
- 使用结果生成可视化图表和洞察。
- 所需资源: 访问数据集、数据分析工具和 SQL 功能的权限。
- 经验: 利用过去的分析结果来提高未来分析的准确性和相关性。
示例:Travel Agent 的代码生成智能体
在这个示例中,我们将设计一个代码生成智能体(Travel Agent),通过生成和执行代码来协助用户规划旅行。该智能体可以利用生成式 AI 处理诸如获取旅行选项、过滤结果以及编制行程等任务。
代码生成智能体概述
- 收集用户偏好: 收集用户的输入,如目的地、旅行日期、预算和兴趣。
- 生成用于获取数据的代码: 生成代码片段以检索有关航班、酒店和景点的数据。
- 执行生成的代码: 运行生成的代码以获取实时信息。
- 生成行程表: 将获取的数据汇编成个性化的旅行计划。
- 基于反馈调整: 接收用户反馈,如有必要则重新生成代码以完善结果。
分步实现
收集用户偏好
Python
class Travel_Agent:
def __init__(self):
self.user_preferences = {}
def gather_preferences(self, preferences):
self.user_preferences = preferences
生成用于获取数据的代码
Python
def generate_code_to_fetch_data(preferences):
# Example: Generate code to search for flights based on user preferences
code = f"""
def search_flights():
import requests
response = requests.get('https://api.example.com/flights', params={preferences})
return response.json()
"""
return code
def generate_code_to_fetch_hotels(preferences):
# Example: Generate code to search for hotels
code = f"""
def search_hotels():
import requests
response = requests.get('https://api.example.com/hotels', params={preferences})
return response.json()
"""
return code
执行生成的代码
Python
def execute_code(code):
# Execute the generated code using exec
exec(code)
result = locals()
return result
travel_agent = Travel_Agent()
preferences = {
"destination": "Paris",
"dates": "2025-04-01 to 2025-04-10",
"budget": "moderate",
"interests": ["museums", "cuisine"]
}
travel_agent.gather_preferences(preferences)
flight_code = generate_code_to_fetch_data(preferences)
hotel_code = generate_code_to_fetch_hotels(preferences)
flights = execute_code(flight_code)
hotels = execute_code(hotel_code)
print("Flight Options:", flights)
print("Hotel Options:", hotels)
生成行程表
Python
def generate_itinerary(flights, hotels, attractions):
itinerary = {
"flights": flights,
"hotels": hotels,
"attractions": attractions
}
return itinerary
attractions = search_attractions(preferences)
itinerary = generate_itinerary(flights, hotels, attractions)
print("Suggested Itinerary:", itinerary)
基于反馈调整
Python
def adjust_based_on_feedback(feedback, preferences):
# Adjust preferences based on user feedback
if "liked" in feedback:
preferences["favorites"] = feedback["liked"]
if "disliked" in feedback:
preferences["avoid"] = feedback["disliked"]
return preferences
feedback = {"liked": ["Louvre Museum"], "disliked": ["Eiffel Tower (too crowded)"]}
updated_preferences = adjust_based_on_feedback(feedback, preferences)
# Regenerate and execute code with updated preferences
updated_flight_code = generate_code_to_fetch_data(updated_preferences)
updated_hotel_code = generate_code_to_fetch_hotels(updated_preferences)
updated_flights = execute_code(updated_flight_code)
updated_hotels = execute_code(updated_hotel_code)
updated_itinerary = generate_itinerary(updated_flights, updated_hotels, attractions)
print("Updated Itinerary:", updated_itinerary)
利用环境感知与推理 (Leveraging environmental awareness and reasoning)
基于表结构的 Schema,确实可以通过利用环境感知和推理来增强查询的生成过程。
以下是如何实现这一点的示例:
- 理解 Schema (Understanding the Schema): 系统将理解表的 Schema 结构,并使用此信息来作为生成查询的基础。
- 基于反馈调整 (Adjusting Based on Feedback): 系统将根据反馈调整用户偏好,并推理出 Schema 中的哪些字段需要被更新。
- 生成并执行查询 (Generating and Executing Queries): 系统将生成并执行查询,以根据新的偏好获取更新后的航班和酒店数据。
以下是结合了这些概念的更新后的 Python 代码示例:
Python
def adjust_based_on_feedback(feedback, preferences, schema):
# Adjust preferences based on user feedback
if "liked" in feedback:
preferences["favorites"] = feedback["liked"]
if "disliked" in feedback:
preferences["avoid"] = feedback["disliked"]
# Reasoning based on schema to adjust other related preferences
for field in schema:
if field in preferences:
preferences[field] = adjust_based_on_environment(feedback, field, schema)
return preferences
def adjust_based_on_environment(feedback, field, schema):
# Custom logic to adjust preferences based on schema and feedback
if field in feedback["liked"]:
return schema[field]["positive_adjustment"]
elif field in feedback["disliked"]:
return schema[field]["negative_adjustment"]
return schema[field]["default"]
def generate_code_to_fetch_data(preferences):
# Generate code to fetch flight data based on updated preferences
return f"fetch_flights(preferences={preferences})"
def generate_code_to_fetch_hotels(preferences):
# Generate code to fetch hotel data based on updated preferences
return f"fetch_hotels(preferences={preferences})"
def execute_code(code):
# Simulate execution of code and return mock data
return {"data": f"Executed: {code}"}
def generate_itinerary(flights, hotels, attractions):
# Generate itinerary based on flights, hotels, and attractions
return {"flights": flights, "hotels": hotels, "attractions": attractions}
# Example schema
schema = {
"favorites": {"positive_adjustment": "increase", "negative_adjustment": "decrease", "default": "neutral"},
"avoid": {"positive_adjustment": "decrease", "negative_adjustment": "increase", "default": "neutral"}
}
# Example usage
preferences = {"favorites": "sightseeing", "avoid": "crowded places"}
feedback = {"liked": ["Louvre Museum"], "disliked": ["Eiffel Tower (too crowded)"]}
updated_preferences = adjust_based_on_feedback(feedback, preferences, schema)
# Regenerate and execute code with updated preferences
updated_flight_code = generate_code_to_fetch_data(updated_preferences)
updated_hotel_code = generate_code_to_fetch_hotels(updated_preferences)
updated_flights = execute_code(updated_flight_code)
updated_hotels = execute_code(updated_hotel_code)
updated_itinerary = generate_itinerary(updated_flights, updated_hotels, feedback["liked"])
print("Updated Itinerary:", updated_itinerary)
解析 - 基于反馈的预订 (Booking Based on Feedback)
- Schema 感知 (Schema Awareness): schema 字典定义了应当如何根据反馈调整偏好。它包含 favorites 和 avoid 等字段,以及相应的调整策略。
调整偏好 (adjust_based_on_feedback 方法): 此方法根据用户反馈和 schema 调整偏好。 - 基于环境的调整 (adjust_based_on_environment 方法): 此方法根据 schema 和反馈定制调整方案。
- 生成并执行查询: 系统生成代码,根据调整后的偏好获取更新后的航班和酒店数据,并模拟执行这些查询。
- 生成行程表: 系统根据新的航班、酒店和景点数据创建更新后的行程表。
通过使系统具备环境感知能力并基于 schema 进行推理,它可以生成更准确、更相关的查询,从而提供更好的旅行建议和更个性化的用户体验。
使用 SQL 作为检索增强生成 (RAG) 技术
SQL(结构化查询语言)是与数据库交互的强大工具。当作为检索增强生成 (RAG) 方法的一部分使用时,SQL 可以从数据库中检索相关数据,以为 AI 智能体生成响应或采取行动提供信息依据。让我们探讨一下在 Travel Agent 的语境中如何将 SQL 作为一种 RAG 技术。
核心概念
- 数据库交互 (Database Interaction):
SQL 用于查询数据库、检索相关信息和操作数据。
示例: 从旅游数据库中获取航班详情、酒店信息和景点。
- 与 RAG 集成 (Integration with RAG):
根据用户输入和偏好生成 SQL 查询。
检索到的数据随后用于生成个性化建议或操作。
- 动态查询生成 (Dynamic Query Generation):
AI 智能体根据上下文和用户需求动态生成 SQL 查询。
示例: 自定义 SQL 查询以根据预算、日期和兴趣过滤结果。
应用场景
- 自动化代码生成: 为特定任务生成代码片段。
- SQL 作为 RAG: 使用 SQL 查询操作数据。
- 解决问题: 创建并执行代码以解决问题。
示例:数据分析智能体:
- 任务:分析数据集寻找趋势。
- 步骤:加载数据集 -> 生成 SQL 查询过滤数据 -> 执行查询检索结果 -> 生成可视化和洞察。
- 资源:数据集访问权限,SQL 能力。
- 经验:使用过去的结果改进未来的分析。
实用示例:在 Travel Agent 中使用 SQL
收集用户偏好
Python
class Travel_Agent:
def __init__(self):
self.user_preferences = {}
def gather_preferences(self, preferences):
self.user_preferences = preferences
生成 SQL 查询
Python
def generate_sql_query(table, preferences):
query = f"SELECT * FROM {table} WHERE "
conditions = []
for key, value in preferences.items():
conditions.append(f"{key}='{value}'")
query += " AND ".join(conditions)
return query
执行 SQL 查询
Python
import sqlite3
def execute_sql_query(query, database="travel.db"):
connection = sqlite3.connect(database)
cursor = connection.cursor()
cursor.execute(query)
results = cursor.fetchall()
connection.close()
return results
生成建议
Python
def generate_recommendations(preferences):
flight_query = generate_sql_query("flights", preferences)
hotel_query = generate_sql_query("hotels", preferences)
attraction_query = generate_sql_query("attractions", preferences)
flights = execute_sql_query(flight_query)
hotels = execute_sql_query(hotel_query)
attractions = execute_sql_query(attraction_query)
itinerary = {
"flights": flights,
"hotels": hotels,
"attractions": attractions
}
return itinerary
travel_agent = Travel_Agent()
preferences = {
"destination": "Paris",
"dates": "2025-04-01 to 2025-04-10",
"budget": "moderate",
"interests": ["museums", "cuisine"]
}
travel_agent.gather_preferences(preferences)
itinerary = generate_recommendations(preferences)
print("Suggested Itinerary:", itinerary)
SQL 查询示例
- 航班查询:
SQL
SELECT * FROM flights WHERE destination='Paris' AND dates='2025-04-01 to 2025-04-10' AND budget='moderate';
- 酒店查询:
SQL
SELECT * FROM hotels WHERE destination='Paris' AND budget='moderate';
- 景点查询:
SQL
SELECT * FROM attractions WHERE destination='Paris' AND interests='museums, cuisine';
通过利用 SQL 作为检索增强生成 (RAG) 技术的一部分,像 Travel Agent 这样的 AI 智能体可以动态地检索和利用相关数据,以提供准确和个性化的推荐。
元认知示例 (Example of Metacognition)
为了演示元认知的实现,让我们创建一个简单的智能体,该智能体在解决问题时会反思自己的决策过程。在这个例子中,我们将构建一个系统:智能体试图优化酒店的选择,但当它犯错或做出次优选择时,它会评估自己的推理并调整策略。
我们将通过一个基本示例来模拟这一点:智能体根据价格和质量的综合情况选择酒店,但它会对其决策进行“反思”并做出相应调整。
这如何说明元认知:
- 初始决策: 智能体将选择最便宜的酒店,而不了解这对质量的影响。
- 反思与评估: 在初步选择之后,智能体将利用用户反馈来检查该酒店是否是一个“糟糕”的选择。如果它发现酒店的质量太低,它就会反思自己的推理逻辑。
- 调整策略: 智能体根据反思调整其策略,从“最便宜 (cheapest)”切换到“最高质量 (highest_quality)”,从而在未来的迭代中改进其决策过程。
示例代码:
Python
class HotelRecommendationAgent:
def __init__(self):
self.previous_choices = [] # Stores the hotels chosen previously
self.corrected_choices = [] # Stores the corrected choices
self.recommendation_strategies = ['cheapest', 'highest_quality'] # Available strategies
def recommend_hotel(self, hotels, strategy):
"""
Recommend a hotel based on the chosen strategy.
The strategy can either be 'cheapest' or 'highest_quality'.
"""
if strategy == 'cheapest':
recommended = min(hotels, key=lambda x: x['price'])
elif strategy == 'highest_quality':
recommended = max(hotels, key=lambda x: x['quality'])
else:
recommended = None
self.previous_choices.append((strategy, recommended))
return recommended
def reflect_on_choice(self):
"""
Reflect on the last choice made and decide if the agent should adjust its strategy.
The agent considers if the previous choice led to a poor outcome.
"""
if not self.previous_choices:
return "No choices made yet."
last_choice_strategy, last_choice = self.previous_choices[-1]
# Let's assume we have some user feedback that tells us whether the last choice was good or not
user_feedback = self.get_user_feedback(last_choice)
if user_feedback == "bad":
# Adjust strategy if the previous choice was unsatisfactory
new_strategy = 'highest_quality' if last_choice_strategy == 'cheapest' else 'cheapest'
self.corrected_choices.append((new_strategy, last_choice))
return f"Reflecting on choice. Adjusting strategy to {new_strategy}."
else:
return "The choice was good. No need to adjust."
def get_user_feedback(self, hotel):
"""
Simulate user feedback based on hotel attributes.
For simplicity, assume if the hotel is too cheap, the feedback is "bad".
If the hotel has quality less than 7, feedback is "bad".
"""
if hotel['price'] < 100 or hotel['quality'] < 7:
return "bad"
return "good"
# Simulate a list of hotels (price and quality)
hotels = [
{'name': 'Budget Inn', 'price': 80, 'quality': 6},
{'name': 'Comfort Suites', 'price': 120, 'quality': 8},
{'name': 'Luxury Stay', 'price': 200, 'quality': 9}
]
# Create an agent
agent = HotelRecommendationAgent()
# Step 1: The agent recommends a hotel using the "cheapest" strategy
recommended_hotel = agent.recommend_hotel(hotels, 'cheapest')
print(f"Recommended hotel (cheapest): {recommended_hotel['name']}")
# Step 2: The agent reflects on the choice and adjusts strategy if necessary
reflection_result = agent.reflect_on_choice()
print(reflection_result)
# Step 3: The agent recommends again, this time using the adjusted strategy
adjusted_recommendation = agent.recommend_hotel(hotels, 'highest_quality')
print(f"Adjusted hotel recommendation (highest_quality): {adjusted_recommendation['name']}")
智能体的元认知能力 (Agents Metacognition Abilities)
这里的核心在于智能体具备以下能力:
- 评估其先前的选择和决策过程。
- 根据这种反思调整其策略——即,执行中的元认知。
这是一种简单形式的元认知,系统能够根据内部反馈调整自身的推理过程。
结论 (Conclusion)
元认知是一个强大的工具,可以显著提升 AI 智能体的能力。通过融入元认知过程,您可以设计出更智能、更具适应性且更高效的智能体。请利用额外的资源进一步探索 AI 智能体元认知这个迷人的世界吧。
你可能也喜欢
- ♥ 智能体检索增强生成05/27
- ♥ 构建值得信赖的 AI 智能体04/19
- ♥ 智能体记忆与自我改进03/14
- ♥ 探索微软智能代理框架12/26
- ♥ AI 智能体的可观测性与评估03/31
- ♥ 多智能体设计模式 (Multi-agent design patterns)04/28

