AI_Agents(十一)_AI智能体编写和执行代码作为工具

4. 生成代码作为工具

Generating Code as a Tool

代码生成型智能体利用 AI 模型编写和执行代码,解决复杂问题并自动化任务。

4.1 代码生成代理

Code Generating Agents

代码生成型智能体利用生成式 AI 模型来编写和执行代码。这些智能体可以通过在多种编程语言中生成和运行代码来解决问题、自动化任务,并提供有价值的见解。

4.1.1 实际应用:Practical Applications

1、Automated Code Generation:

自动化代码生成:为特定任务生成代码片段,例如数据分析、网络抓取或机器学习。

2、SQL as a RAG:使用 SQL 查询从数据库中检索和操作数据。

3、Problem Solving:

问题解决:创建和执行代码以解决特定问题,例如优化算法或数据分析。

4.1.2 示例:数据分析代码生成代理

Example: Code Generating Agent for Data Analysis

想象你正在设计一个代码生成代理。它可能的工作方式如下:

1)Task:

任务:分析数据集以识别趋势和模式。

2)Steps:

步骤:

  • 将数据集加载到数据分析工具中。
  • 生成 SQL 查询以过滤和聚合数据。
  • 执行查询并检索结果。
  • 利用结果生成可视化和洞察。

3)Required Resources:

所需资源:数据集访问权限、数据分析工具和 SQL 能力。

4)Experience:

经验:利用过去的分析结果来提高未来分析的准确性和相关性。

4.1.3 示例:旅行代理代码生成代理

在这个示例中,我们将设计一个代码生成代理——旅行代理,通过生成和执行代码来帮助用户规划旅行。这个代理可以处理诸如获取旅行选项、筛选结果以及使用生成式 AI 编制行程等任务。

代码生成代理概述

  1. Gathering User Preferences:

    收集用户偏好:收集用户输入,如目的地、旅行日期、预算和兴趣。

  2. Generating Code to Fetch Data:

    生成代码以获取数据:生成代码片段以检索关于航班、酒店和景点的信息。

  3. Executing Generated Code:

    执行生成代码:运行生成代码以获取实时信息。

  4. Generating Itinerary:

    生成行程:将获取的数据编译成个性化的旅行计划。

  5. Adjusting Based on Feedback:

    根据反馈调整:接收用户反馈并在必要时重新生成代码以优化结果。

4.1.4 逐步实现

1)收集用户偏好:Gathering User Preferences

class Travel_Agent:
    def __init__(self):
        self.user_preferences = {}

    def gather_preferences(self, preferences):
        self.user_preferences = preferences

2)生成用于获取数据的代码:Generating Code to Fetch Data

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

这个 f"""..."""Python 的 f-string(格式化字符串字面量),它的作用是将字符串中的花括号 {} 内的变量或表达式自动替换为它们的值。

  • f"""...""" 开头的字符串是一个 多行格式化字符串
  • {preferences} 是一个占位符,会被当前作用域下名为 preferences 的变量的值替换。
  • 最终 code 变量中保存的是一段字符串代码,其中 {preferences} 已被替换成实际内容。

eg:

假设你之前有定义:

preferences = {'from': 'NYC', 'to': 'LAX'}

那么:

print(code)

输出将是:

def search_flights():
    import requests
    response = requests.get('<https://api.example.com/flights>', params={'from': 'NYC', 'to': 'LAX'})
    return response.json()

3)执行生成代码:Executing Generated Code

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)

4)生成行程:Generating Itinerary

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)

5)根据反馈进行调整:Adjusting Based on Feedback

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)

4.2 利用环境意识和推理

Leveraging environmental awareness and reasoning

根据表格的架构确实可以通过利用环境感知和推理来增强查询生成过程。

  1. Understanding the Schema:

    理解模式:系统将理解表格的模式,并使用这些信息来支撑查询生成。

  2. Adjusting Based on Feedback:

    根据反馈调整:系统将根据反馈调整用户偏好,并推理模式中哪些字段需要更新。

  3. Generating and Executing Queries:

    生成和执行查询:系统将生成并执行查询,根据新的偏好获取更新的航班和酒店数据。

这里是一个包含这些概念的更新后的 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)

解释 - 基于反馈的预订

Explanation - Booking Based on Feedback

  1. Schema Awareness:

    模式感知: schema 字典定义了如何根据反馈调整偏好。它包括 favorites 和 avoid 等字段,并对应相应的调整。

  2. Adjusting Preferences (adjust_based_on_feedback method):

    调整偏好( adjust_based_on_feedback 方法):此方法根据用户反馈和模式调整偏好。

  3. Environment-Based Adjustments (adjust_based_on_environment method):

    基于环境的调整( adjust_based_on_environment 方法):此方法根据模式和反馈定制调整。

  4. Generating and Executing Queries:

    生成和执行查询:系统根据调整后的偏好生成代码以获取更新的航班和酒店数据,并模拟这些查询的执行。

  5. Generating Itinerary:

    生成行程:系统根据新的航班、酒店和景点数据创建更新的行程。

举个例子说明:

feedback = {
    "liked": ["museum", "weather"],
    "disliked": ["crowd"]
}

schema = {
    "museum": {
        "positive_adjustment": 2,
        "negative_adjustment": -2,
        "default": 0
    },
    "weather": {
        "positive_adjustment": 3,
        "negative_adjustment": -1,
        "default": 1
    },
    "crowd": {
        "positive_adjustment": 1,
        "negative_adjustment": -3,
        "default": 0
    }
}

现在调用函数:

adjust_based_on_environment(feedback, "museum", schema)

输出为:

2  # 因为 "museum" 在 feedback["liked"] 中,所以返回 positive_adjustment

调用:

adjust_based_on_environment(feedback, "crowd", schema)

输出:

-3  # 因为 "crowd" 在 feedback["disliked"] 中

通过使系统环境感知并基于模式进行推理,它可以生成更准确和相关的查询,从而带来更好的旅行推荐和更个性化的用户体验。


这个函数是一个“环境感知调整器”,

  • 它会根据用户的喜好或厌恶,
  • 按照预设规则(schema)返回一个数值(或其他内容),
  • 常用于推荐系统、评分系统、偏好权重调整等场景。

1-30 —— 是 "调整值"(adjustment values),它们的含义取决于具体的上下文,一般代表对某个推荐因子的加权调整,用于模型或逻辑判断时改变该项的重要程度。

一般含义如下:

值类型示例值含义
正数+1, +2, +3表示喜欢/推荐倾向,越大表示用户越偏好这个字段,对推荐系统加分
负数-1, -2, -3表示厌恶/不推荐倾向,越小表示用户越不喜欢这个字段,推荐系统应降低其权重或排除
0表示中性/默认态度,用户没有特别表达好恶,维持默认值即可

4.3 使用 SQL 作为RAG技术

Using SQL as a Retrieval-Augmented Generation (RAG) Technique

SQL(结构化查询语言 Structured Query Language)是一种强大的数据库交互工具。当作为检索增强生成(RAG)方法的一部分使用时,SQL 可以从数据库中检索相关数据,以指导 AI 代理生成响应或执行操作。让我们探讨 SQL 如何在旅行代理的背景下作为 RAG 技术使用。

4.3.1 关键概念

  1. 数据库交互:Database Interaction:
    • SQL 用于查询数据库、检索相关信息以及操作数据。
    • 示例:从旅游数据库中获取航班详情、酒店信息和景点信息。
  2. 与 RAG 集成:Integration with RAG:
    • SQL 查询基于用户输入和偏好生成。
    • 检索到的数据随后用于生成个性化推荐或操作。
  3. 动态查询生成:Dynamic Query Generation
    • AI 代理根据上下文和用户需求生成动态 SQL 查询。
    • 示例:根据预算、日期和兴趣自定义 SQL 查询以筛选结果。

4.3.2 应用:Applications

  • Automated Code Generation:

    自动代码生成:为特定任务生成代码片段。

  • SQL as a RAG:

    SQL 作为 RAG:使用 SQL 查询操作数据。

  • Problem Solving:

    问题解决:创建并执行代码以解决问题。

示例:数据分析代理

Example: A data analysis agent

  1. Task:

    任务:分析数据集以发现趋势。

  2. Steps:

    步骤:

    • 加载数据集。
    • 生成 SQL 查询以筛选数据。
    • 执行查询并检索结果。
    • 生成可视化和洞察。
  3. Resources:

    资源:数据集访问,SQL 功能。

  4. Experience:

    经验:利用历史结果改进未来分析。

4.3.3 实际案例:旅行代理中使用 SQL

  1. 收集用户偏好:Gathering User Preferences

    class Travel_Agent:
        def __init__(self):
            self.user_preferences = {}
    
        def gather_preferences(self, preferences):
            self.user_preferences = preferences
    
  2. 生成 SQL 查询:Generating SQL Queries

    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
    

    这段代码定义了一个函数 generate_sql_query(table, preferences),它的作用是:根据用户提供的 表名(table偏好条件(preferences,动态生成一条 SQL 查询语句。


    def generate_sql_query(table, preferences):
    

    定义函数,接收两个参数:

    • table: 表名,例如 "flights""hotels"
    • preferences: 一个字典,表示查询条件,例如:{"city": "Paris", "price": "low"}

        query = f"SELECT * FROM {table} WHERE "
    

    生成 SQL 查询语句的开头,例如:

    SELECT * FROM flights WHERE
    

    
        conditions = []
        for key, value in preferences.items():
            conditions.append(f"{key}='{value}'")
    

    遍历偏好字典,把每一项都转为 SQL 条件,比如:

    "city='Paris'"
    "price='low'"
    

    最终 conditions 是一个列表:["city='Paris'", "price='low'"]


        query += " AND ".join(conditions)
    

    将条件拼接成完整的 WHERE 子句,用 " AND " 连接。


        return query
    

    返回拼接好的完整 SQL 查询语句。


    假设:

    table = "flights"
    preferences = {"city": "Paris", "price": "low"}
    

    函数执行后返回:

    SELECT * FROM flights WHERE city='Paris' AND price='low'
    
  3. 执行 SQL 查询:Executing SQL Queries

    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
    

    这段代码定义了一个函数 execute_sql_query,用于连接本地 SQLite 数据库并执行一条 SQL 查询语句,最后返回查询结果。


    import sqlite3
    

    引入 Python 内置的 sqlite3 模块,用于操作 .db 本地数据库文件。


    def execute_sql_query(query, database="travel.db")
    

    定义函数 execute_sql_query,有两个参数:

    • query: 要执行的 SQL 查询语句(字符串类型);
    • database: 要连接的数据库文件名,默认为 "travel.db"

        connection = sqlite3.connect(database)
    

    打开并连接到 SQLite 数据库 travel.db(如果文件不存在,会自动创建)。


        cursor = connection.cursor()
    

    获取数据库“游标”,用于执行 SQL 操作。


        cursor.execute(query)
    

    执行传入的 SQL 查询语句,例如:

    SELECT * FROM hotels WHERE city='Paris';
    

        results = cursor.fetchall()
    

    获取执行结果的全部行,返回的是一个包含元组的列表,例如:

    [("Paris", "Hotel A", 3), ("Paris", "Hotel B", 4)]
    

        connection.close()
    

    关闭数据库连接,释放资源(非常重要)。


        return results
    

    返回查询结果给调用者。

  4. 生成推荐:Generating Recommendations

    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 查询:Example SQL Queries

  1. 航班查询:Flight Query

    SELECT * FROM flights WHERE destination='Paris' AND dates='2025-04-01 to 2025-04-10' AND budget='moderate';
    
  2. 酒店查询:Hotel Query

    SELECT * FROM hotels WHERE destination='Paris' AND budget='moderate';
    
  3. 吸引力查询Attraction Query

    SELECT * FROM attractions WHERE destination='Paris' AND interests='museums, cuisine';
    

通过将 SQL 作为检索增强生成(RAG)技术的一部分,像旅行代理这样的 AI 代理可以动态检索并利用相关数据,以提供准确和个性化的推荐。

5. 元认知示例

Example of Metacongition

因此,为了展示元认知的实现,让我们创建一个简单的智能体,它在解决问题时会反思自己的决策过程。在这个例子中,我们将构建一个系统,其中智能体试图优化酒店的选择,但当它犯错或做出次优选择时,会评估自己的推理并调整策略

我们将通过一个基本示例来模拟这个过程,其中智能体根据价格和质量组合来选择酒店,但它会“反思”其决策并进行相应调整。

5.1 如何体现元认知

How this illustrates metacognition:

  1. Initial Decision:

    初始决策:智能体将选择最便宜的酒店,而不理解质量影响。

  2. Reflection and Evaluation:

    反思与评估:在初始选择后,智能体会通过用户反馈检查酒店是否是“糟糕”的选择。如果发现酒店质量太低,它会反思自己的推理过程。

  3. Adjusting Strategy:

    调整策略:智能体根据反思调整策略,从“最便宜”转向“最高质量”,从而在未来迭代中改进其决策过程。

e.g.

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']}")

5.2 智能体元认知能力

关键在于智能体的能力:

  • 评估其先前的选择和决策过程。
  • 根据这种反思调整其策略,即元认知在行动中。

这是一种简单的元认知形式,系统能够根据内部反馈调整其推理过程。

6. 结论

元认知是一种强大的工具,可以显著提升 AI 代理的能力。通过融入元认知过程,你可以设计出更智能、更适应性强、更高效的代理。利用附加资源,进一步探索 AI 代理中元认知的迷人世界。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值