TellWorldAI 世界档案
问档案English

首页›实践›实践

实践

让智能体学会自我反思(元认知)

让智能体评估自己的选择并调整策略。用一个酒店推荐的小例子跑通反思循环,并注意示例里 exec 和拼接 SQL 的风险。

这篇适合谁,读完能做到什么

适合想让智能体在出错之后调整自己做法的开发者。读完你能写出一个会评估自己选择、根据反馈换策略的小型推荐智能体,并知道示例代码里哪些地方不能直接用到生产环境。

元认知是什么

元认知指对自己思考过程的思考。对智能体来说,就是基于自我认知和过往经验,评估并调整自己的行动。这种能力可以帮助智能体应对几类问题:透明度(能解释自己的推理和决策)、推理(综合信息做出合理判断)、适应(适应新环境和变化的条件),以及感知(更准确地识别和理解环境中的数据)。[1]

具体到智能体的价值,主要有四点:自我反思(评估自己的表现,找出可改进之处)、适应性(根据过往经验和环境变化调整策略)、纠错(自主发现并修正错误)、资源管理(用规划和评估来节约时间和算力)。[1]

智能体由哪些部分组成

一个 AI 智能体通常包含三部分:人设(persona),即它与用户互动的风格和特点;工具(tools),即它能执行的功能;技能(skills),即它掌握的知识和专长。三者合在一起,构成一个能完成具体任务的「专业单元」。[1]

先看一个旅行智能体的反思

以帮用户规划巴黎之行的旅行智能体为例,它的任务分四步:收集用户偏好(日期、预算、兴趣和特殊需求)、检索航班、住宿和景点信息、生成个性化行程,再根据反馈调整。[1]

反思发生在最后这一步之后。它会查看用户反馈,判断哪些推荐受欢迎、哪些不受欢迎,并据此调整以后的建议。例如,用户表示不喜欢拥挤的地方,它就不再在高峰时段推荐热门景点;如果推荐过一家其实已经订满的酒店,它以后会更严格地核对房态。[1]

动手:做一个会反思的酒店推荐智能体

下面的例子只用到标准库,没有调用大模型。它有两种推荐策略:cheapest(最便宜)和 highest_quality(质量最高)。

  1. 定义智能体。它保存两类记录:之前的选择和纠正后的选择,并提供两种策略。推荐方法根据策略挑出一家酒店,再把结果记到 previous_choices 里。[1]
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
  1. 写反思方法。它读取上一次的选择,拿到反馈。反馈为 bad 时,在两种策略之间切换,并把纠正后的选择记下来;否则直接报告「选择很好」。[1]
    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."
  1. 用模拟反馈替代真实用户。示例的规则很简单:价格低于 100 或质量低于 7 的酒店,反馈为 bad。[1]
    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"
  1. 准备数据并按顺序运行:先用 cheapest 推荐,再反思,最后用调整后的策略再推荐一次。[1]
# 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']}")

按代码的逻辑推算:第一步最便宜的是 Budget Inn(80,质量 6),模拟反馈判它为 bad,于是策略切换为 highest_quality;第三步推荐的是质量最高的 Luxury Stay(200,质量 9)。这就是一个最简的元认知循环:评估上一次的选择,再根据评估改变策略。[1]

和检索增强生成的关系

检索增强生成(RAG)既可以是一种提示技巧,也可以是一个工具。作为提示技巧,开发者为每次检索手写具体的查询,控制力强,但要花心思调提示词;作为工具,RAG 内置在智能体的架构里,自动完成检索和生成,集成更容易,规模大时效率更高。[1]

纠正式 RAG(corrective RAG)包含三部分:提示技巧引导检索,工具评估检索结果的相关性并生成准确的回答,评估环节则持续检查表现并加以调整。[1]

预先加载上下文(pre-emptive context load)是另一种做法:在处理查询之前,把相关的背景信息先装进模型,它从一开始就掌握这些信息,不必在过程中再去检索。[1]

相关性评估与搜索意图

评估相关性时,评估时有四个关键概念:上下文理解、准确性、用户意图和反馈循环。[1]

一个简单的做法是给每个候选项打分。下面的函数在类别符合兴趣、价格在预算内、位置与目的地一致时,各加一分:[1]

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

打分之后按分数从高到低排序,取前十个:[1]

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

用户意图通常分三类:信息型(如「巴黎最好的博物馆有哪些」)、导航型(如「卢浮宫官网」)和交易型(如「订一张去巴黎的机票」)。示例用关键词粗略判断意图:[1]

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"

关键词判断只是入门级的做法,真实系统一般会结合上下文、用户历史和自然语言处理来理解意图。[1]

代码生成和 SQL 的风险

代码生成型智能体会让模型写代码再执行。示例用 exec 直接运行生成的代码,并没有展示任何隔离措施。这在本地演示里可以接受,接到真实系统前必须放进受限环境,例如容器,并限制它能访问的资源。[1]

def execute_code(code):
    # Execute the generated code using exec
    exec(code)
    result = locals()
    return result

示例中的 SQL 辅助函数,是把偏好值用 f-string 直接拼进查询语句,并没有使用参数化查询。偏好里如果混入了恶意内容,就可能改变 SQL 的含义。这一点在写生产代码时要避免。[1]

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

限制和常见问题

  • 示例中的用户反馈是模拟的,规则固定。真实系统要接入用户的真实反馈,并考虑反馈本身可能有偏差。[1]
  • 示例只在两种固定策略之间切换,不会学习新的策略。要做更完整的自我改进,需要更多的策略和更好的评估标准。[1]
  • 反思是在每次推荐之后才发生的。想在执行过程中就发现问题,需要在更早的环节设置检查点。

下一步

示例全部是教学用的简化代码,没有错误处理,也没有真实的酒店或航班接口。想了解智能体上线之后的评测与监控,可以接着读「智能体上线(AI Agents in Production)」这一主题。[1]

本文改编自 Microsoft 开源课程《AI Agents for Beginners》第 9 课[1],原文以 MIT 许可证发布。

来源

  1. 1
    Metacognition in AI AgentsMicrosoft ai-agents-for-beginners (MIT)

引用本页: 让智能体学会自我反思(元认知). TellWorld, https://www.tellworld.net/zh/practice/practice-agent-metacognition. 更新于 2026-11-14

相关动态