AgentScope : 与CodeAct智能体对话

news2024/9/30 7:16:53

参考:
非一般程序猿第六季Agent入门实战篇(三)–CodeActAgent篇
Conversation with CodeAct Agent

0,简介

CodeAct Agent是一个Agent,它不仅可以聊天,还可以为你编写和执行Python代码。在本示例中,将介绍另一种赋予Agent调用工具能力的方法,特别是通过直接向Agent提供工具的相应代码,然后允许Agent独立地使用它们。

在工具使用方面,CodeAct Agent还允许Agent使用工具(Tools)来解决问题,但是以不同的方式。

pip install notebook nbclient nbformat

1,AgentScope 模型和角色配置

1.1 AgentScope 模型配置

跟之前AgentScope中带有@功能的多Agent组对话一样,配置 model_config.json

[
    {
        "model_type": "dashscope_chat",
        "config_name": "dashscope_qwen_max_chat-temperature-0.1",
        "model_name": "qwen-max",
        "api_key": "换成你自己的key",
        "generate_args": {
            "temperature": 0.1
        }
    }{
        "model_type": "dashscope_chat",
        "config_name": "dashscope_qwen_turbe_chat-temperature-0.5",
        "model_name": "qwen-turbo",
        "api_key": "换成你自己的key",
        "generate_args": {
            "temperature": 0.5
        }
    }
]

1.2 初始化 model config

import agentscope
...
agentscope.init(
        model_configs="./configs/model_configs.json",
        project="Conversation with CodeAct Agent",
    )
...

1.3 初始化CodeAct Agent

定义CodeAct Agent 类(codeact_agent.py)

# -*- coding: utf-8 -*-
# pylint: disable=C0301
"""An agent class that implements the CodeAct agent.
This agent can execute code interactively as actions.
More details can be found at the paper of CodeAct agent
https://arxiv.org/abs/2402.01030
and the original repo of codeact https://github.com/xingyaoww/code-act
一个实现了CodeAct代理的代理类。
该代理可以交互式地执行代码作为动作。
更多细节可以在CodeAct代理的论文
https://arxiv.org/abs/2402.01030
"""
from agentscope.agents import AgentBase
from agentscope.message import Msg
from agentscope.service import (
    ServiceResponse,
    ServiceExecStatus,
    NoteBookExecutor,
)
from agentscope.parsers import RegexTaggedContentParser

# SYSTEM_MESSAGE = """
# You are a helpful assistant that gives helpful, detailed, and polite answers to the user's questions.
# You should interact with the interactive Python (Jupyter Notebook) environment and receive the corresponding output when needed. The code written by assistant should be enclosed using <execute> tag, for example: <execute> print('Hello World!') </execute>.
# You should attempt fewer things at a time instead of putting too much code in one <execute> block. You can install packages through PIP by <execute> !pip install [package needed] </execute> and should always import packages and define variables before starting to use them.
# You should stop <execute> and provide an answer when they have already obtained the answer from the execution result. Whenever possible, execute the code for the user using <execute> instead of providing it.
# Your response should be concise, but do express their thoughts. Always write the code in <execute> block to execute them.
# You should not ask for the user's input unless necessary. Solve the task on your own and leave no unanswered questions behind.
# You should do every thing by your self.
# """  # noqa
# 系统消息
SYSTEM_MESSAGE = """
你是一个乐于助人的助手,会给出对用户问题的详细、礼貌的回答。
你应该与交互式的Python(Jupyter Notebook)环境进行交互,并在需要时接收相应的输出。
助手编写的代码应使用<execute>标签括起来,例如:<execute> print('Hello World!') </execute>。
你应该每次都尽量少做一些事情,而不是在一个<execute>块中放太多代码。
你可以通过<execute> !pip install [所需包] </execute>安装包,并且在开始使用之前始终导入包并定义变量。
当已经从执行结果中获得答案时,你应该停止<execute>并提供答案。
尽可能地为用户执行代码,而不是提供代码。
你的回答应尽量简明扼要,但也要表达出用户的想法。
你应该在必要时才询问用户的输入。独立解决问题,不留未解答的问题。
你应该独立完成所有任务。
"""
# EXAMPLE_MESSAGE = """
# Additionally, you are provided with the following code available:
# {example_code}
# The above code is already available in your interactive Python (Jupyter Notebook) environment, allowing you to directly use these variables and functions without needing to redeclare them.
# """  # noqa

# 示例代码消息
EXAMPLE_MESSAGE = """
此外,你还可以使用以下代码:
{example_code}
上述代码已经在你的交互式Python(Jupyter Notebook)环境中可用,允许你直接使用这些变量和函数,而无需重新声明它们。
"""

class CodeActAgent(AgentBase):
    """
    The implementation of CodeAct-agent.
    The agent can execute code interactively as actions.
    More details can be found at the paper of codeact agent
    https://arxiv.org/abs/2402.01030
    and the original repo of codeact https://github.com/xingyaoww/code-act
    """
    """
    CodeAct代理的实现。
    该代理可以作为 动作 交互式地执行代码。
    更多细节可以在CodeAct代理的论文
    https://arxiv.org/abs/2402.01030
    和原始的codeact仓库 https://github.com/xingyaoww/code-act 中找到
    """

    def __init__(
        self,
        name: str,
        model_config_name: str,
        example_code: str = "",
    ) -> None:
        """
        Initialize the CodeActAgent.
        Args:
            name(`str`):
                The name of the agent.
            model_config_name(`str`):
                The name of the model configuration.
            example_code(Optional`str`):
                The example code to be executed bewfore the interaction.
                You can import reference libs, define variables and functions to be called. For example:

                    ```python
                    from agentscope.service import bing_search
                    import os

                    api_key = "{YOUR_BING_API_KEY}"

                    def search(question: str):
                        return bing_search(question, api_key=api_key, num_results=3).content
                    ```

        """  # noqa
        """
        初始化CodeActAgent。
        参数:
            name(str):
                代理的名称。
            model_config_name(str):
                模型配置的名称。
            example_code(str, 可选):
                在交互前执行的示例代码。
                你可以导入参考库,定义变量和函数。例如:

                    ```python
                    from agentscope.service import bing_search
                    import os

                    api_key = "{YOUR_BING_API_KEY}"

                    def search(question: str):
                        return bing_search(question, api_key=api_key, num_results=3).content
                    ```
        """

        # 调用父类的初始化方法
        super().__init__(
            name=name,
            model_config_name=model_config_name,
        )
        # 最大执行次数
        self.n_max_executions = 5
        # 示例代码
        self.example_code = example_code
        # 代码执行器
        self.code_executor = NoteBookExecutor()

        # 系统消息
        sys_msg = Msg(name="system", role="system", content=SYSTEM_MESSAGE)
        # 示例消息
        example_msg = Msg(
            name="user",
            role="user",
            content=EXAMPLE_MESSAGE.format(example_code=self.example_code),
        )

        # 将系统消息添加到内存
        self.memory.add(sys_msg)

        # 如果有示例代码,则执行并记录结果
        if self.example_code != "":
            # 代码执行结果
            code_execution_result = self.code_executor.run_code_on_notebook(
                self.example_code,
            )
            # 代码执行消息
            code_exec_msg = self.handle_code_result(
                code_execution_result,
                "Example Code excuted: ",
            )
            self.memory.add(example_msg)
            self.memory.add(code_exec_msg)
            self.speak(code_exec_msg)

        # 解析器
        self.parser = RegexTaggedContentParser(try_parse_json=False)

    def handle_code_result(
        self,
        code_execution_result: ServiceResponse,
        content_pre_sring: str = "",
    ) -> Msg:
        """return the message from code result"""
        """
        返回代码执行结果的消息
        """
        code_exec_content = content_pre_sring
        if code_execution_result.status == ServiceExecStatus.SUCCESS:
            code_exec_content += "Excution Successful:\n"
        else:
            code_exec_content += "Excution Failed:\n"
        code_exec_content += "Execution Output:\n" + str(
            code_execution_result.content,
        )
        return Msg(name="user", role="user", content=code_exec_content)

    def reply(self, x: Msg = None) -> Msg:
        """The reply function that implements the codeact agent."""
        """
        实现codeact代理的回复函数。
        """
        self.memory.add(x)

        # 执行计数
        excution_count = 0
        while (
            self.memory.get_memory(1)[-1].role == "user"
            and excution_count < self.n_max_executions # 最大执行次数
        ):
            prompt = self.model.format(self.memory.get_memory())
            model_res = self.model(prompt) # 模型响应
            msg_res = Msg(
                name=self.name,
                content=model_res.text,
                role="assistant",
            )
            self.memory.add(msg_res)
            self.speak(msg_res)
            res = self.parser.parse(model_res)
            code = res.parsed.get("execute")
            if code is not None:
                code = code.strip()
                code_execution_result = (
                    self.code_executor.run_code_on_notebook(code)
                )
                excution_count += 1
                code_exec_msg = self.handle_code_result(code_execution_result)
                self.memory.add(code_exec_msg)
                self.speak(code_exec_msg)

        if excution_count == self.n_max_executions:
            assert self.memory.get_memory(1)[-1].role == "user"
            code_max_exec_msg = Msg(
                name="assitant",
                role="assistant",
                content=(
                    "I have reached the maximum number "
                    f"of executions ({self.n_max_executions=}). "
                    "Can you assist me or ask me another question?"
                ),
            )
            self.memory.add(code_max_exec_msg)
            self.speak(code_max_exec_msg)
            return code_max_exec_msg

        return msg_res

初始化 CodeAct Agent

YOUR_MODEL_CONFIGURATION_NAME = "dashscope_qwen_turbo_chat-temperature-0.1"

YOUR_MODEL_CONFIGURATION = {
    "model_type": "dashscope_chat", 
    "config_name": YOUR_MODEL_CONFIGURATION_NAME
    
    # ...
}

from codeact_agent import CodeActAgent

import agentscope

agentscope.init(model_configs=YOUR_MODEL_CONFIGURATION)

import nest_asyncio
nest_asyncio.apply()
agent = CodeActAgent(
    name="assistant",
    model_config_name=YOUR_MODEL_CONFIGURATION_NAME,
)

1.4 要求 CodeAct Agent 执行任务


from loguru import logger
from agentscope.message import Msg

mss = Msg(
    name="user", 
    content="Given y = 0.9x + 6.1, randomly sample data points as pairs of (x, y). Then fit a linear regression on the sampled data and plot the points, fitted line, and ground-truth line.", 
    role="user"
)
logger.chat(mss)
answer_mss1 = agent(mss)

运行结果:

C:\Users\admin\miniconda3\envs\agentscope\python.exe C:/Users/admin/wws/github_project/agentscope/examples/conversation_with_codeact_agent/main.py
2024-09-29 18:52:36.157 | INFO     | agentscope.manager._model:load_model_configs:115 - Load configs for model wrapper: dashscope_qwen_max_chat-temperature-0.5, dashscope_qwen_turbo_chat-temperature-0.1, gpt-4, my_post_api
2024-09-29 18:52:36.165 | INFO     | agentscope.models.model:__init__:203 - Initialize model by configuration [dashscope_qwen_turbo_chat-temperature-0.1]
C:\Users\admin\miniconda3\envs\agentscope\lib\site-packages\zmq\_future.py:724: RuntimeWarning: Proactor event loop does not implement add_reader family of methods required for zmq. Registering an additional selector thread for add_reader support via tornado. Use `asyncio.set_event_loop_policy(WindowsSelectorEventLoopPolicy())` to avoid this warning.
  self._get_loop()
user: Given y = 0.9x + 6.1, randomly sample data points as pairs of (x, y). Then fit a linear regression on the sampled data and plot the points, fitted line, and ground-truth line.
assistant: To accomplish this task, I will follow these steps:

1. Generate random `x` values within a reasonable range.
2. Use the equation `y = 0.9x + 6.1` to compute the corresponding `y` values for each `x`.
3. Add some noise to the `y` values to simulate real-world data variability.
4. Split the data into training and testing sets (though for simplicity and since you didn't specify, we'll just use all the data for fitting).
5. Fit a linear regression model on the generated data.
6. Plot the original data points, the fitted line from the regression, and the ground-truth line.

Let's start by generating the data points and fitting the regression model.

[execute]
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression

# Set a seed for reproducibility
np.random.seed(42)

# Generate random x values between 0 and 100
x_values = np.random.rand(100) * 100

# Compute the corresponding y values without noise
y_values_ground_truth = 0.9 * x_values + 6.1

# Add some noise to y values
noise = np.random.normal(0, 10, size=x_values.shape)
y_values_noisy = y_values_ground_truth + noise

# Combine into a single dataset
data = np.column_stack((x_values, y_values_noisy))

# Fit a linear regression model
model = LinearRegression()
model.fit(data[:, 0].reshape(-1, 1), data[:, 1])

# Prepare to plot
plt.figure(figsize=(10, 6))
[/execute]
user: Execution Output:
['<Figure size 1000x600 with 0 Axes>', 'Unsupported display type']
assistant: It seems there was an issue with displaying the plot directly here. No worries, I will still generate the plot and save it to a file instead, which you can view separately. Let me adjust the code to save the plot as an image file.

[execute]
# Plotting the data points, fitted line, and ground-truth line
plt.scatter(data[:, 0], data[:, 1], label='Sampled Data', color='blue')
plt.plot(data[:, 0], model.predict(data[:, 0].reshape(-1, 1)), label='Fitted Line', color='red', linestyle='--')
plt.plot(data[:, 0], y_values_ground_truth, label='Ground-Truth Line', color='green')

plt.title('Linear Regression on Sampled Data')
plt.xlabel('X')
plt.ylabel('Y')
plt.legend()
plt.grid(True)

# Save the plot to a file
plt.savefig('linear_regression_plot.png')
plt.close()
[/execute]

The plot has been saved as 'linear_regression_plot.png'. You can view this file to see the sampled data points, the fitted line from the linear regression, and the ground-truth line based on the equation `y = 0.9x + 6.1`. If you need further analysis or have any other requests, feel free to ask!
user: Execution Output:
[]
assistant: It appears the output confirmation was suppressed in this environment, but typically, when running the code locally or in a supported environment, you would see a message indicating the plot was successfully saved to 'linear_regression_plot.png'.

Since we cannot directly view the saved file here, trust that the file has been created with the following components:

- **Sampled Data Points**: Represented as blue dots, scattered according to the generated `x` values and the noisy `y` values.
- **Fitted Line**: Shown as a red dashed line, representing the linear regression model's prediction based on the sampled data.
- **Ground-Truth Line**: Displayed as a green line, illustrating the true relationship defined by `y = 0.9x + 6.1`.

If you need further assistance or another operation, such as analyzing the quality of the fit or re-running the process with different parameters, please let me know!


在这里插入图片描述

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

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

相关文章

Mac 卸载 IDEA 流程

1、现在应用程序中删除Idea 2、进入Library目录 cd /Users/zhengzhaoxiang/Library 3、删除IntelliJIdea2023.3&#xff08;根据自己的版本而定&#xff09;记得进去看下是否删除干净了 rm -rf Logs/JetBrains/IntelliJIdea2023.3 rm -rf Preferences/com.jetbrains.intel…

项目学习笔记

Downloads – Oracle VirtualBoxhttps://www.virtualbox.org/wiki/Downloads

启动hadoop集群出现there is no HDFS_NAMENODE_USER defined.Aborting operation

解决方案 在hadoop-env.sh中添加 export HDFS_DATANODE_USERroot export HDFS_NAMENODE_USERroot export HDFS_SECONDARYNAMENODE_USERroot export YARN_RESOURCEMANAGER_USERroot export YARN_NODEMANAGER_USERroot 再次运行即可。

Candance仿真电流镜OTA

1.电路图搭建 图1 上面那层不能直接一横直接连过来&#xff0c;图2只能这样连。但是&#xff0c;图2的M1和M0的电压已经超过了VDD的1.8V。是不行的&#xff0c;需要调整&#xff0c;主要增大M1和M0的宽长比以减小电压。 图2 candance电流镜OTA电路实现 下面这篇文章讲了电流镜…

ROS与无人驾驶学习笔记(一)——ROS基本操作

文章目录 ※ 安装ubuntu 下载 创建虚拟机 安装系统 安装vmware tool 更新源 安装常用软件 ※ 安装ROS 设置软件更新 使用清华源安装 ros测试 认识ROS ROS特点 ROS系统实现 ROS安装 工作需要&#xff0c;转行做码农了。。。 大概是无人驾驶相关的&#xff0c;啥都不会。。。 看成…

JS设计模式之状态模式:优雅地管理应用中产生的不同状态

一. 前言 在过去&#xff0c;我们经常使用条件语句&#xff08;if-else 语句&#xff09;来处理应用程序中的不同状态。然而&#xff0c;这种方式往往会让代码变得冗长、难以维护&#xff0c;并可能引入潜在的 bug。而状态模式则提供了一种更加结构化和可扩展的方法来处理状态…

支持超高分辨率图片生成,UltraPixel模型分享

UltraPixel是一种由华为诺亚方舟实验室联合香港科技大学共同开发的超高清图像合成架构&#xff0c;旨在生成具有丰富细节的高质量图像&#xff0c;其分辨率可以从1K一直延伸至6K。 UltraPixel不仅仅是一个图像放大工具&#xff0c;它还能在生成过程中优化细节&#xff0c;提升…

Golang | Leetcode Golang题解之第447题回旋镖的数量

题目&#xff1a; 题解&#xff1a; func numberOfBoomerangs(points [][]int) (ans int) {for _, p : range points {cnt : map[int]int{}for _, q : range points {dis : (p[0]-q[0])*(p[0]-q[0]) (p[1]-q[1])*(p[1]-q[1])cnt[dis]}for _, m : range cnt {ans m * (m - 1)…

Go实现RabbitMQ消息模式

【目标】 go实现RabbitMQ简单模式和work工作模式 go实现RabbitMQ 消息持久化和手动应答 go实现RabbitMQ 发布订阅模式 go使用MQ实现评论后排行榜更新 1. go实现简单模式 编写路由实现生产消息 实现生产消息 MQ消息执行为命令行执行&#xff0c;所以创建命令行执行函数mai…

react-native-Windows配置

一&#xff1a;官网&#xff1a; React Native for Windows macOS Build native Windows & macOS apps with Javascript and React 二&#xff1a;安装依赖 需要以管理员身份运行powershell,然后粘贴下面代码&#xff0c;注意&#xff1a;要安装淘宝镜像&#xff0c;要…

JAVA线程基础二——锁的概述之乐观锁与悲观锁

乐观锁与悲观锁 乐观锁和悲观锁是在数据库中引入的名词,但是在并发包锁里面也引入了类似的思想&#xff0c;所以这里还是有必要讲解下。 悲观锁指对数据被外界修改持保守态度&#xff0c;认为数据很容易就会被其他线程修改&#xff0c;所以在数据被处理前先对数据进行加锁&…

[Redis][典型运用][分布式锁]详细讲解

目录 0.什么是分布式锁1.分布式锁的基础实现2.引入过期时间3.引入校验ID4.引入Lua5.引入Watch Dog(看门狗)6.引入Redlock算法7.其他功能 0.什么是分布式锁 在⼀个分布式的系统中&#xff0c;也会涉及到多个节点访问同⼀个公共资源的情况&#xff0c;此时就需要通过锁来做互斥控…

一拖二快充线:单接与双接的多场景应用

在当代社会&#xff0c;随着智能手机等电子设备的普及&#xff0c;充电问题成为了人们关注的焦点。一拖二快充线作为一种创新的充电解决方案&#xff0c;因其便捷性与高效性而受到广泛关注。本文将深入探讨一拖二快充线的定义、原理以及在单接与双接手机场景下的应用&#xff0…

数字图像处理:空间域滤波

1.数字图像处理&#xff1a;空间域滤波 1.1 滤波器核&#xff08;相关核&#xff09;与卷积 图像上的邻域计算 线性空间滤波的原理 滤波器核&#xff08;相关核&#xff09;是如何得到的&#xff1f; 空间域的卷积 卷积&#xff1a;滤波器核与window中的对应值相乘后所有…

touch命令:创建文件,更新时间戳

一、命令简介 ​touch​ 命令在 Linux 和其他类 Unix 系统中用于创建空白文件或者更新已存在文件的时间戳。如果指定的文件不存在&#xff0c;touch​ 命令会创建一个空白文件&#xff1b;如果文件已经存在&#xff0c;touch​ 命令会更新文件的访问时间和修改时间&#xff0c…

誉天Linux云计算课程学什么?为什么保障就业?

一个IT工程师相当于干了哪些职业? 其中置顶回答生动而形象地描绘道&#xff1a; 一个IT工程师宛如一个超级多面手&#xff0c;相当于——加班狂程序员测试工程师实施工程师网络工程师电工装卸工搬运工超人。 此中酸甜苦辣咸&#xff0c;相信很多小伙伴们都深有体会。除了典…

用开源软件制作出精美的短视频#视频编辑

从前&#xff0c;有一个叫做创意森林的地方&#xff0c;住着各种各样的编辑精灵。一天&#xff0c;视频编辑精灵们发现了一本神秘的论文&#xff0c;里面写满了如何利用前沿的AI技术来提升他们的工作效率。于是&#xff0c;精灵们开始学习使用LLM和LLaVA&#xff0c;像魔法一样…

《企业实战分享 · 开发技术栈选型》

&#x1f4e2; 大家好&#xff0c;我是 【战神刘玉栋】&#xff0c;有10多年的研发经验&#xff0c;致力于前后端技术栈的知识沉淀和传播。 &#x1f497; &#x1f33b; CSDN入驻不久&#xff0c;希望大家多多支持&#xff0c;后续会继续提升文章质量&#xff0c;绝不滥竽充数…

02Cesium中常用的鼠标事件

文章目录 02Cesium中常用的鼠标事件1、左键单击事件2、左键双击事件3、左键按下事件4、左键弹起事件5、中键按下事件6、中键弹起事件7、鼠标移动事件8、右键单击事件9、右键按下事件10、右键弹起事件11、鼠标滚轮事件具体在代码中的应用如下所示 02Cesium中常用的鼠标事件 Ces…

windows下安装rabbitMQ并开通管理界面和允许远程访问

如题&#xff0c;在windows下安装一个rabbitMQ server&#xff1b;然后用浏览器访问其管理界面&#xff1b;由于rabbitMQ的默认账号guest默认只能本机访问&#xff0c;因此需要设置允许其他机器远程访问。这跟mysql的思路很像&#xff0c;默认只能本地访问&#xff0c;要远程访…