AutoGen实战AI Agent开发

news2024/9/21 14:30:07

最近,关于 AI 智能体或AI代理(AI Agent)的讨论很多。受这种炒作的影响,我阅读了一些资料,偶然发现了 AutoGen,这是一个构建 AI 代理的很棒的库。但 AI 代理到底是什么?为什么它们很重要?让我们深入研究一下。

LLM 已经存在了几年,它们正在迅速向 AI 代理和 Agentic 工作流程发展。别误会我的意思,LLM 很棒,但它们在自行实现自动化方面仍然效率不高。通过消耗大量语言数据,LLM 与其他工具相结合是一种非常有效的方式,可以充分利用 LLM 所拥有的通用智能。AI 代理是可以自主执行任务的软件实体,可以与环境交互以做出决策。它们正在彻底改变我们解决问题的方式,从客户服务聊天机器人到复杂的数据分析。今天,我很高兴向你展示如何使用 AutoGen 构建一个简单的 AI 代理。

准备好了吗?让我们开始吧!

NSDT工具推荐: Three.js AI纹理开发包 - YOLO合成数据生成器 - GLTF/GLB在线编辑 - 3D模型格式在线转换 - 可编程3D场景编辑器 - REVIT导出3D模型插件 - 3D模型语义搜索引擎 - Three.js虚拟轴心开发包 - 3D模型在线减面 - STL模型在线切割 

1、为什么 AI 代理很重要

AI 代理带来了几个好处:

  • 自动化:它们无需人工干预即可处理重复性任务。
  • 效率:它们处理数据和执行任务的速度比人类更快。
  • 可扩展性:它们可以全天候运行,提供服务而无需停机。
  • 智能:它们从交互中学习和改进,随着时间的推移变得越来越好。

鉴于这些优势,AI 代理正在被从医疗保健到金融等各个行业采用。

2、使用 AutoGen 构建一个简单的 AI 代理

让我们动手使用 AutoGen 构建一个基本的 AI 代理。为了进行演示,我们将解决 LeetCode 中的“在二叉树中分配硬币”问题。这个问题是编码面试中的经典问题,你需要在数组中找到两个相加等于目标的数字。Colab 链接请点击这里。

2.1 安装 AutoGen

首先,我们需要安装 AutoGen 库。在你的环境中运行以下命令:

!pip install pyautogen -q --progress-bar off

2.2 设置你的环境

我使用 Google Colab 进行此演示。以下是如何设置你的环境并安全地加载你的 OpenAI API 密钥:

import os
import autogen
from google.colab import userdata

# Load your OpenAI API key
userdata.get('OPENAI_API_KEY')

llm_config = {
    "config_list": [{"model": "gpt-3.5-turbo", "api_key": userdata.get('OPENAI_API_KEY')}],
    "cache_seed": 0,
    "temperature": 0,
}

2.3 定义问题

我们将使用 LeetCode 中的 LC Medium“在二叉树中分配硬币”问题:

LEETCODE_QUESTION = """
Title : Distribute Coins in a binary tree

You are given the root of a binary tree with n nodes where each node in the tree has node.val coins. There are n coins in total throughout the whole tree.

In one move, we may choose two adjacent nodes and move one coin from one node to another. A move may be from parent to child, or from child to parent.

Return the minimum number of moves required to make every node have exactly one coin.

 

Example 1:


Input: root = [3,0,0]
Output: 2
Explanation: From the root of the tree, we move one coin to its left child, and one coin to its right child.
Example 2:


Input: root = [0,3,0]
Output: 3
Explanation: From the left child of the root, we move two coins to the root [taking two moves]. Then, we move one coin from the root of the tree to the right child.

Follow-up: Can you come up with an algorithm that has a better time complexity?
"""

4、设置代理

AutoGen 使用两种类型的代理: AssistantAgent 和 UserProxyAgent

AssistantAgent 建议代码解决方案,而 UserProxyAgent 执行代码并检查其是否正常工作:

SYSTEM_MESSAGE = """You are a helpful AI assistant. Solve tasks using your coding and language skills..."""

assistant = autogen.AssistantAgent(
    name="assistant",
    llm_config=llm_config,
    system_message=SYSTEM_MESSAGE
)

user_proxy = autogen.UserProxyAgent(
    name="user_proxy",
    human_input_mode="NEVER",
    max_consecutive_auto_reply=4,
    is_termination_msg=lambda x: x.get("content", "").rstrip().endswith("TERMINATE"),
    code_execution_config={
        "work_dir": "coding",
        "use_docker": False,
    },
)

human_input_mode 设置为“NEVER”,因为我们不打算自己提供任何输入,而 max_consecutive_auto_reply 限制了对话轮次。

5、发起对话

我们将通过从 UserProxyAgent 向我们的助手发送消息来开始对话。

with autogen.Cache.disk(cache_seed=7) as cache:
  chat_res = user_proxy.initiate_chat(
      assistant,
      message="""Solve the following LeetCode problem and also comment on its time and space complexity:\n\n""" + LEETCODE_QUESTION
  )

以下是输出对话的片段:

user_proxy (to assistant):

Solve the following LeetCode problem and also comment on its time and space complexity:


Title : Distribute Coins in a binary tree

You are given the root of a binary tree with n nodes where each node in the tree has node.val coins. There are n coins in total throughout the whole tree.

In one move, we may choose two adjacent nodes and move one coin from one node to another. A move may be from parent to child, or from child to parent.

Return the minimum number of moves required to make every node have exactly one coin.

 

Example 1:


Input: root = [3,0,0]
Output: 2
Explanation: From the root of the tree, we move one coin to its left child, and one coin to its right child.
Example 2:


Input: root = [0,3,0]
Output: 3
Explanation: From the left child of the root, we move two coins to the root [taking two moves]. Then, we move one coin from the root of the tree to the right child.

Follow-up: Can you come up with an algorithm that has a better time complexity?


--------------------------------------------------------------------------------
assistant (to user_proxy):

To solve this problem, we can perform a depth-first search (DFS) traversal of the binary tree and calculate the excess coins at each node. The excess coins at a node can be calculated as the sum of coins at the node and the excess coins from its left and right children, minus 1 (since the node itself should have 1 coin).

Here is the Python code to solve the problem:

```python
class Solution:
    def distributeCoins(self, root: TreeNode) -> int:
        self.moves = 0
        
        def dfs(node):
            if not node:
                return 0
            
            left_excess = dfs(node.left)
            right_excess = dfs(node.right)
            
            self.moves += abs(left_excess) + abs(right_excess)
            
            return node.val + left_excess + right_excess - 1
        
        dfs(root)
        
        return self.moves
```

Time complexity analysis:
- The DFS traversal visits each node once, so the time complexity is O(n), where n is the number of nodes in the binary tree.

Space complexity analysis:
- The space complexity is O(h), where h is the height of the binary tree. This is due to the recursive calls in the DFS traversal. In the worst case, the space complexity can be O(n) for a skewed tree.

To improve the time complexity, we can modify the algorithm to avoid redundant calculations and achieve a linear time complexity. This can be done by returning both the excess coins and the number of moves from the DFS function. This way, we can eliminate the need to traverse the tree twice.

--------------------------------------------------------------------------------

>>>>>>>> EXECUTING CODE BLOCK 0 (inferred language is python)...
user_proxy (to assistant):

exitcode: 1 (execution failed)
Code output: 
Traceback (most recent call last):
  File "", line 1, in <module>
    class Solution:
  File "", line 2, in Solution
    def distributeCoins(self, root: TreeNode) -> int:
NameError: name 'TreeNode' is not defined

注意 UserProxyAgent 是如何出错的。它会回调另一个代理来获取解决方案:

--------------------------------------------------------------------------------
assistant (to user_proxy):

It seems like the code snippet I provided is missing the definition of the `TreeNode` class. Here is an updated version of the code that includes the definition of the `TreeNode` class:

```python
# Definition for a binary tree node.
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

class Solution:
    def distributeCoins(self, root: TreeNode) -> int:
        self.moves = 0
        
        def dfs(node):
            if not node:
                return 0
            
            left_excess = dfs(node.left)
            right_excess = dfs(node.right)
            
            self.moves += abs(left_excess) + abs(right_excess)
            
            return node.val + left_excess + right_excess - 1
        
        dfs(root)
        
        return self.moves
```

You can now use this updated code to solve the LeetCode problem "Distribute Coins in a binary tree".

--------------------------------------------------------------------------------

>>>>>>>> EXECUTING CODE BLOCK 0 (inferred language is python)...
user_proxy (to assistant):

exitcode: 0 (execution succeeded)
Code output: 


--------------------------------------------------------------------------------
assistant (to user_proxy):

Great! I'm glad to hear that the code executed successfully. If you have any more questions or need further assistance, feel free to ask!

--------------------------------------------------------------------------------
user_proxy (to assistant):



--------------------------------------------------------------------------------
assistant (to user_proxy):

If you have any more questions or need help with anything else, feel free to ask. I'm here to help!

--------------------------------------------------------------------------------
user_proxy (to assistant):



--------------------------------------------------------------------------------
assistant (to user_proxy):

If you have any questions in the future or need assistance, don't hesitate to ask. Have a great day!

--------------------------------------------------------------------------------

6、结束语

通过使用 AutoGen 的可对话代理,我们自动验证了 LLM 建议的 Python 代码是否有效,并创建了一个框架,LLM 可以通过读取控制台输出来响应语法或逻辑错误。


原文链接:AutoGen实战AI智能体 - BimAnt

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1928778.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

移动UI:表单美观易操作的十大准则,非常实用。

移动端表单设计需要遵循一些原则&#xff0c;以确保美观和易操作&#xff1a; 1.简洁明了&#xff1a; 在移动端表单设计中&#xff0c;要尽量简化内容&#xff0c;避免过多的文字和元素&#xff0c;保持简洁明了的布局&#xff0c;以便用户能够快速理解并填写表单。 2.响应式…

在 PostgreSQL 中如何优化涉及多个视图嵌套和函数调用的复杂查询?

&#x1f345;关注博主&#x1f397;️ 带你畅游技术世界&#xff0c;不错过每一次成长机会&#xff01;&#x1f4da;领书&#xff1a;PostgreSQL 入门到精通.pdf 文章目录 在 PostgreSQL 中如何优化涉及多个视图嵌套和函数调用的复杂查询一、理解问题的本质二、优化的基本原则…

直播美颜工具开发教学:视频美颜SDK集成详解

本篇文章&#xff0c;笔者将详细介绍如何在直播应用中集成视频美颜SDK&#xff0c;让你的直播画面焕然一新。 一、什么是视频美颜SDK&#xff1f; 视频美颜SDK是一种软件开发工具包&#xff0c;提供了视频处理和图像增强功能。通过集成视频美颜SDK&#xff0c;开发者可以轻松…

【postgresql】角色(Role)

PostgreSQL 中&#xff0c;角色&#xff08;Role&#xff09;是一个重要的概念&#xff0c;用于管理数据库的访问权限和用户身份。角色可以被视为用户或组&#xff0c;具体取决于它们的配置方。 角色属性 角色可以具有多种属性&#xff1a; LOGIN&#xff1a;允许角色登录数据…

Apple Vision Pro 和其商业未来

机器人、人工智能相关领域 news/events &#xff08;专栏目录&#xff09; 本文目录 一、Vision Pro 生态系统二、Apple Vision Pro 的营销用例 随着苹果公司备受期待的进军可穿戴计算领域&#xff0c;新款 Apple Vision Pro 承载着巨大的期望。 苹果公司推出的 Vision Pro 售…

2024.7.12单片机PWM

遇到了一个光标变成下划线的问题&#xff1a; Keil5光标变下划线&#xff0c;变回来的方法_keil5光标是下划线-CSDN博客 这里是用了输入捕获&#xff08;IC&#xff1a;input capture&#xff09;&#xff0c;输出比较&#xff08;OC:Output Compare&#xff09;区别 学到这…

[Linux]添加sudoers

之前我们讲过sudo这个命令,它可以让我们普通用户进行短暂的提权,上回我们讲完了vim 本篇是个短篇,目的就是让我们之后的学习中可以使用sudo命令。 首先我们先登录root用户 ls /etc/sudoer 我们需要改的就是上面的这个文件 vim /etc/sudoers 我们用vim打开 把光标移动到这…

17-8 向量数据库之野望8 - 7 个主流向量数据库

​​​​​​ 在快速发展的人工智能 (AI)、机器学习 (ML) 和数据工程领域,对高效数据存储和检索系统的需求至关重要。矢量数据库已成为管理这些技术通常依赖的复杂高维数据的关键解决方案。在这里,我们探讨了每个 AI/ML/数据工程师都应该熟悉的七个矢量数据库,重点介绍了它们…

mysql-connector-java 8.0.33 反序列化漏洞

前言 经过与oracle官方沟通&#xff0c;在最新的mysql-connector-j 9.0.0里不存在这个问题&#xff0c;所以他们不认为这是个漏洞 不过确实&#xff0c;mysql-connector-java这个分支已经迁移到mysql-connector-j了&#xff0c;当时没注意&#xff0c;交的时候只注意了mysql-c…

全球DeepFake攻防挑战赛DataWhale AI 夏令营——图像赛道

全球DeepFake攻防挑战赛&DataWhale AI 夏令营——图像赛道 赛题背景 随着人工智能技术的迅猛发展&#xff0c;深度伪造技术&#xff08;Deepfake&#xff09;正成为数字世界中的一把双刃剑。这项技术不仅为创意内容的生成提供了新的可能性&#xff0c;同时也对数字安全构…

数学建模·模糊评价法

模糊评价法 一种解决评价问题或者得出最佳方案的方法 主观性仍比较强 具体定义 三集&#xff1a;因素集&#xff0c;评语集和权重集&#xff0c;通过模拟矩阵的处理得到最合理的评语 具体步骤 因素集 因素集的确定不难&#xff0c;难在对分级评价时&#xff0c;对因素集的分级…

MYSQL--第九次作业

MYSQL–第九次作业 1、安装redis&#xff0c;启动客户端、验证。 安装网址&#xff1a;Redis Released&#xff0c;找到适合自己电脑的redis版本后&#xff0c;下载并安装。 安装完后&#xff0c;打开cmd命令框&#xff1a; -- 启动客户端 C:\Windows\System32>redis-cl…

AV1 编码标准帧间预测技术概述

AV1 编码标准帧间预测 AV1&#xff08;AOMedia Video1&#xff09;是一种开源的视频编码格式&#xff0c;它在帧间预测技术上做出了显著的改进和扩展&#xff0c;以提供比现有标准更高的压缩效率和更好的视频质量。以下是AV1帧间预测技术的几个关键点&#xff1a; 参考帧扩展&a…

STM32(五):STM32指南者-按键控制灯开关实验

说明&#xff1a;源代码和教程可从野火处下载&#xff0c;本博客为了记录学习过程STM32&#xff08;四&#xff09;&#xff1a;STM32指南者-跑马灯实验的基础上 一、采用轮询方式1、bsp_key.h2、bsp_key.c3、main.c 二、采用中断方式1、bsp_exti.h2、bsp_exti.c3、stm32f10x_i…

【动态规划1】斐波那契数列模型篇

文章目录 声明动态规划介绍1137.第N个泰波那契数题目描述分析代码 面试题 08.01. 三步问题题目描述分析代码 746.使用最小花费爬楼梯题目描述分析代码 91.解码⽅法题目描述分析代码 声明 本篇博客为动态规的基础篇&#xff0c;从零开始学习动态规划&#xff0c;如有错误&#…

14、Python之super star:一颗星、两颗星,满天都是小星星

引言 关于Python系列的文章&#xff0c;已经通过两篇文章&#xff0c;介绍了Python中关于函数的简单使用&#xff0c;包括为什么要使用函数&#xff0c;以及函数中带默认值参数的使用注意事项。 之后&#xff0c;岔开函数的主题&#xff0c;通过几篇番外篇&#xff0c;重点谈…

PHP恋爱话术微信小程序系统源码

&#x1f496;恋爱高手的秘密武器&#xff01;恋爱话术微信小程序&#xff0c;让情话信手拈来✨ &#x1f4ad;【开场白&#xff1a;恋爱路上的甜蜜助手】&#x1f4ad; 还在为跟心仪的TA聊天时找不到话题而尴尬&#xff1f;或是担心自己说的每句话都显得那么“直男/女”&…

YOLOv8改进 | 检测头 | 融合渐进特征金字塔的检测头【AFPN3】

秋招面试专栏推荐 &#xff1a;深度学习算法工程师面试问题总结【百面算法工程师】——点击即可跳转 &#x1f4a1;&#x1f4a1;&#x1f4a1;本专栏所有程序均经过测试&#xff0c;可成功执行&#x1f4a1;&#x1f4a1;&#x1f4a1; 专栏目录 &#xff1a;《YOLOv8改进有效…

文件安全传输系统,如何保障信创环境下数据的安全传输?

文件安全传输系统是一套旨在保护数据在传输过程中的安全性和完整性的技术或解决方案。通常包括以下几个关键组件&#xff1a; 加密&#xff1a;使用强加密算法来确保文件在传输过程中不被未授权访问。 身份验证&#xff1a;确保只有授权用户才能访问或传输文件。 完整性校验…

数据库管理-第220期 Oracle的高可用-03(20240715)

数据库管理220期 2024-07-15 数据库管理-第220期 Oracle的高可用-03&#xff08;20240715&#xff09;1 AC/TAC2 配置Service3 用户权限4 端口开放总结 数据库管理-第220期 Oracle的高可用-03&#xff08;20240715&#xff09; 作者&#xff1a;胖头鱼的鱼缸&#xff08;尹海文…