AutoGen实现多代理-Tool_Use_and_Conversational_Chess(四)

1. 学习背景 在这里插入图片描述

如图,常见的Agent之间交流对话,可能会涉及到外部工具的调用和嵌套式聊天,这种设计模式就要求代理会使用工具和按序执行代码。本节尝试聊天机器人模拟人类进行下棋,如图所示,Chess Board代理则进行检测合法性并记录移动。
在这里插入图片描述

2. 代码实践

本节实验链接:传送门

2.1 准备环境

llm_config = {"model": "gpt-4-turbo"}# 导入与棋盘相关的包
import chess
import chess.svg
from typing_extensions import Annotated# 初始化棋盘
board = chess.Board()
made_move = False

2.2 定义所需的工具

2.2.1 获取合法移动的工具

def get_legal_moves() -> Annotated[str, "A list of legal moves in UCI format"]:return "Possible moves are: " + ",".join([str(move) for move in board.legal_moves])

2.2.2 在棋盘上进行移动的工具

def make_move(move: Annotated[str, "A move in UCI format."]
) -> Annotated[str, "Result of the move."]:move = chess.Move.from_uci(move)board.push_uci(str(move))global made_movemade_move = True# Display the board.display(chess.svg.board(board,arrows=[(move.from_square, move.to_square)],fill={move.from_square: "gray"},size=200))# Get the piece name.piece = board.piece_at(move.to_square)piece_symbol = piece.unicode_symbol()piece_name = (chess.piece_name(piece.piece_type).capitalize()if piece_symbol.isupper()else chess.piece_name(piece.piece_type))return f"Moved {piece_name} ({piece_symbol}) from "\f"{chess.SQUARE_NAMES[move.from_square]} to "\f"{chess.SQUARE_NAMES[move.to_square]}."

2.3 创建代理

你将为棋盘创建玩家代理和棋盘代理。

from autogen import ConversableAgent
# Player white agent
player_white = ConversableAgent(name="Player White",system_message="You are a chess player and you play as white. ""First call get_legal_moves(), to get a list of legal moves. ""Then call make_move(move) to make a move.",llm_config=llm_config,
)
# Player black agent
player_black = ConversableAgent(name="Player Black",system_message="You are a chess player and you play as black. ""First call get_legal_moves(), to get a list of legal moves. ""Then call make_move(move) to make a move.",llm_config=llm_config,
)
def check_made_move(msg):global made_moveif made_move:made_move = Falsereturn Trueelse:return False
board_proxy = ConversableAgent(name="Board Proxy",llm_config=False,is_termination_msg=check_made_move,default_auto_reply="Please make a move.",human_input_mode="NEVER",
)

2.4 为代理注册可用的工具

调用工具的代理和执行工具的代理都必须为其注册一个工具。

from autogen import register_function
# 为每个代理都注册合法性检测工具和移动工具,方便代理调用
for caller in [player_white, player_black]:register_function(get_legal_moves,caller=caller,executor=board_proxy,name="get_legal_moves",description="Get legal moves.",)register_function(make_move,caller=caller,executor=board_proxy,name="make_move",description="Call this tool to make a move.",)

可以查看代理绑定工具的情况

player_black.llm_config["tools"]

输出如下:

[{'type': 'function','function': {'description': 'Get legal moves.','name': 'get_legal_moves','parameters': {'type': 'object', 'properties': {}, 'required': []}}},{'type': 'function','function': {'description': 'Call this tool to make a move.','name': 'make_move','parameters': {'type': 'object','properties': {'move': {'type': 'string','description': 'A move in UCI format.'}},'required': ['move']}}}]

2.5 注册嵌套式聊天模式

每个玩家代理将与棋盘代理进行嵌套式聊天,以便在棋盘上进行移动。

player_white.register_nested_chats(trigger=player_black,chat_queue=[{"sender": board_proxy,"recipient": player_white,"summary_method": "last_msg",}],
)player_black.register_nested_chats(trigger=player_white,chat_queue=[{"sender": board_proxy,"recipient": player_black,"summary_method": "last_msg",}],
)

2.6 开始游戏

board = chess.Board()chat_result = player_black.initiate_chat(player_white,message="Let's play chess! Your move.",max_turns=2,
)

输出如下:

Player Black (to Player White):Let's play chess! Your move.-------------------------------------------------------------------------------->>>>>>>> USING AUTO REPLY...********************************************************************************
Starting a new chat....********************************************************************************
Board Proxy (to Player White):Let's play chess! Your move.-------------------------------------------------------------------------------->>>>>>>> USING AUTO REPLY...
Player White (to Board Proxy):***** Suggested tool call (call_Xp271IKAeUo1TxQvoHZ4dWae): get_legal_moves *****
Arguments: 
{}
********************************************************************************-------------------------------------------------------------------------------->>>>>>>> EXECUTING FUNCTION get_legal_moves...
Board Proxy (to Player White):Board Proxy (to Player White):***** Response from calling tool (call_Xp271IKAeUo1TxQvoHZ4dWae) *****
Possible moves are: g1h3,g1f3,b1c3,b1a3,h2h3,g2g3,f2f3,e2e3,d2d3,c2c3,b2b3,a2a3,h2h4,g2g4,f2f4,e2e4,d2d4,c2c4,b2b4,a2a4
**********************************************************************-------------------------------------------------------------------------------->>>>>>>> USING AUTO REPLY...
Player White (to Board Proxy):***** Suggested tool call (call_XanM9YQcrNYeqGH23xy5Mphx): make_move *****
Arguments: 
{"move":"e2e4"}
**************************************************************************-------------------------------------------------------------------------------->>>>>>>> EXECUTING FUNCTION make_move...
Board Proxy (to Player White):Board Proxy (to Player White):***** Response from calling tool (call_XanM9YQcrNYeqGH23xy5Mphx) *****
Moved pawn (♙) from e2 to e4.
**********************************************************************-------------------------------------------------------------------------------->>>>>>>> USING AUTO REPLY...
Player White (to Board Proxy):I've moved my pawn from e2 to e4. Your turn!--------------------------------------------------------------------------------
Player White (to Player Black):I've moved my pawn from e2 to e4. Your turn!-------------------------------------------------------------------------------->>>>>>>> USING AUTO REPLY...********************************************************************************
Starting a new chat....********************************************************************************
Board Proxy (to Player Black):I've moved my pawn from e2 to e4. Your turn!-------------------------------------------------------------------------------->>>>>>>> USING AUTO REPLY...
Player Black (to Board Proxy):***** Suggested tool call (call_iNPpTbzXbXjXvkrBir5eMoXg): get_legal_moves *****
Arguments: 
{}
********************************************************************************-------------------------------------------------------------------------------->>>>>>>> EXECUTING FUNCTION get_legal_moves...
Board Proxy (to Player Black):Board Proxy (to Player Black):***** Response from calling tool (call_iNPpTbzXbXjXvkrBir5eMoXg) *****
Possible moves are: g8h6,g8f6,b8c6,b8a6,h7h6,g7g6,f7f6,e7e6,d7d6,c7c6,b7b6,a7a6,h7h5,g7g5,f7f5,e7e5,d7d5,c7c5,b7b5,a7a5
**********************************************************************-------------------------------------------------------------------------------->>>>>>>> USING AUTO REPLY...
Player Black (to Board Proxy):I'll move my pawn from e7 to e5.Let's execute that move.
***** Suggested tool call (call_OeCdklYTQCRCf3zbDTN4Iyhh): make_move *****
Arguments: 
{"move":"e7e5"}
**************************************************************************-------------------------------------------------------------------------------->>>>>>>> EXECUTING FUNCTION make_move...
Board Proxy (to Player Black):Board Proxy (to Player Black):***** Response from calling tool (call_OeCdklYTQCRCf3zbDTN4Iyhh) *****
Moved pawn (♟) from e7 to e5.
**********************************************************************-------------------------------------------------------------------------------->>>>>>>> USING AUTO REPLY...
Player Black (to Board Proxy):I moved my pawn from e7 to e5. It's your turn!--------------------------------------------------------------------------------
Player Black (to Player White):I moved my pawn from e7 to e5. It's your turn!-------------------------------------------------------------------------------->>>>>>>> USING AUTO REPLY...********************************************************************************
Starting a new chat....********************************************************************************
Board Proxy (to Player White):I moved my pawn from e7 to e5. It's your turn!-------------------------------------------------------------------------------->>>>>>>> USING AUTO REPLY...
Player White (to Board Proxy):***** Suggested tool call (call_OIZtgdPww7usovnyFNVQuaf2): get_legal_moves *****
Arguments: 
{}
********************************************************************************-------------------------------------------------------------------------------->>>>>>>> EXECUTING FUNCTION get_legal_moves...
Board Proxy (to Player White):Board Proxy (to Player White):***** Response from calling tool (call_OIZtgdPww7usovnyFNVQuaf2) *****
Possible moves are: g1h3,g1f3,g1e2,f1a6,f1b5,f1c4,f1d3,f1e2,e1e2,d1h5,d1g4,d1f3,d1e2,b1c3,b1a3,h2h3,g2g3,f2f3,d2d3,c2c3,b2b3,a2a3,h2h4,g2g4,f2f4,d2d4,c2c4,b2b4,a2a4
**********************************************************************-------------------------------------------------------------------------------->>>>>>>> USING AUTO REPLY...
Player White (to Board Proxy):***** Suggested tool call (call_o8palhCreQqCGalX2GDOezvj): make_move *****
Arguments: 
{"move":"e2e4"}
**************************************************************************-------------------------------------------------------------------------------->>>>>>>> EXECUTING FUNCTION make_move...
Board Proxy (to Player White):Board Proxy (to Player White):***** Response from calling tool (call_o8palhCreQqCGalX2GDOezvj) *****
Error: illegal uci: 'e2e4' in rnbqkbnr/pppp1ppp/8/4p3/4P3/8/PPPP1PPP/RNBQKBNR w KQkq - 0 2
**********************************************************************-------------------------------------------------------------------------------->>>>>>>> USING AUTO REPLY...
Player White (to Board Proxy):It seems there was a misunderstanding; your move, pawn from e7 to e5, has already been reflected on the board. I'll proceed with my move now. Let me make another valid move.
***** Suggested tool call (call_IOkzRwgZ2V61IJeprXUGSbyk): make_move *****
Arguments: 
{"move":"g1f3"}
**************************************************************************-------------------------------------------------------------------------------->>>>>>>> EXECUTING FUNCTION make_move...
Board Proxy (to Player White):Board Proxy (to Player White):***** Response from calling tool (call_IOkzRwgZ2V61IJeprXUGSbyk) *****
Moved knight (♘) from g1 to f3.
**********************************************************************-------------------------------------------------------------------------------->>>>>>>> USING AUTO REPLY...
Player White (to Board Proxy):I've moved my knight from g1 to f3. It's your turn!--------------------------------------------------------------------------------
Player White (to Player Black):I've moved my knight from g1 to f3. It's your turn!--------------------------------------------------------------------------------

jupyternotebook执行过程有图,因博客原因,图片复制不出来,见谅。

2.7 为游戏添加有趣的闲聊!

player_white = ConversableAgent(name="Player White",system_message="You are a chess player and you play as white. ""First call get_legal_moves(), to get a list of legal moves. ""Then call make_move(move) to make a move. ""After a move is made, chitchat to make the game fun.",llm_config=llm_config,
)
player_black = ConversableAgent(name="Player Black",system_message="You are a chess player and you play as black. ""First call get_legal_moves(), to get a list of legal moves. ""Then call make_move(move) to make a move. ""After a move is made, chitchat to make the game fun.",llm_config=llm_config,
)
for caller in [player_white, player_black]:register_function(get_legal_moves,caller=caller,executor=board_proxy,name="get_legal_moves",description="Get legal moves.",)register_function(make_move,caller=caller,executor=board_proxy,name="make_move",description="Call this tool to make a move.",)player_white.register_nested_chats(trigger=player_black,chat_queue=[{"sender": board_proxy,"recipient": player_white,"summary_method": "last_msg","silent": True,}],
)player_black.register_nested_chats(trigger=player_white,chat_queue=[{"sender": board_proxy,"recipient": player_black,"summary_method": "last_msg","silent": True,}],
)
board = chess.Board()chat_result = player_black.initiate_chat(player_white,message="Let's play chess! Your move.",max_turns=2,
)

输出如下:

Player Black (to Player White):Let's play chess! Your move.-------------------------------------------------------------------------------->>>>>>>> USING AUTO REPLY...********************************************************************************
Starting a new chat....********************************************************************************>>>>>>>> USING AUTO REPLY...>>>>>>>> EXECUTING FUNCTION get_legal_moves...>>>>>>>> USING AUTO REPLY...>>>>>>>> EXECUTING FUNCTION make_move...>>>>>>>> USING AUTO REPLY...
Player White (to Player Black):Great! I've moved my pawn to e4. It's your turn now. How do you like to open your games when you play chess? Do you prefer more aggressive openings or a solid, defensive setup?-------------------------------------------------------------------------------->>>>>>>> USING AUTO REPLY...********************************************************************************
Starting a new chat....********************************************************************************>>>>>>>> USING AUTO REPLY...>>>>>>>> EXECUTING FUNCTION get_legal_moves...>>>>>>>> USING AUTO REPLY...>>>>>>>> EXECUTING FUNCTION make_move...>>>>>>>> USING AUTO REPLY...
Player Black (to Player White):The pawn has moved to e5, and now I'm looking forward to seeing your next strategy. It seems like we are gearing up for a classical open game!Tell me about your chess experiences. Have you had any memorable games or achievements that stand out in your journey as a chess player?-------------------------------------------------------------------------------->>>>>>>> USING AUTO REPLY...********************************************************************************
Starting a new chat....********************************************************************************>>>>>>>> USING AUTO REPLY...>>>>>>>> EXECUTING FUNCTION get_legal_moves...>>>>>>>> USING AUTO REPLY...>>>>>>>> USING AUTO REPLY...>>>>>>>> EXECUTING FUNCTION make_move...>>>>>>>> USING AUTO REPLY...
Player White (to Player Black):I've moved the pawn from d2 to d4, which opens up lines for our bishop and queen and contests the center directly against the black e5 pawn. This is a classic central strategy aiming to seize spatial advantage.Now, as the game becomes more complex and tense, what’s your favorite opening to play in chess and why? Do you prefer tactical skirmishes or strategic, positional battles?--------------------------------------------------------------------------------

3. 总结

本篇内容以下棋为案例,模拟了三个不同代理的嵌套式聊天,最大的特点是允许代理可以使用定义的工具,扩展了代理的功能。此外,嵌套式工作流是可以借鉴的地方,如何让多代理进行嵌套式聊天,从而解决问题是一个不错的思路。

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

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

相关文章

【CSS Tricks】css动画详解

目录 引言一、动画关键帧序列二、动画各属性拆解1. animation-name2. animation-duration3. animation-delay3.1 设置delay为正值3.2 设置delay为负值 4. animation-direction5. animation-iteration-count6. animation-fill-mode7. animation-play-state8. animation-timing-f…

【大牛!】3DMAX城市交通插件CityTraffic使用方法详解

3dMax城市交通插件CityTraffic有助于在城市环境和越野环境中创建汽车交通流。特殊的道路编辑器和自动汽车设置大大加快了交通运动模拟场景的准备速度。 每辆车的配置多种多样,无论是悬架支架的调整还是驾驶风格,都能够创建逼真的模拟。动力学计算使复杂表面的运动更加真实,…

qt使用QDomDocument读写xml文件

在使用QDomDocument读写xml之前需要在工程文件添加: QT xml 1.生成xml文件 void createXml(QString xmlName) {QFile file(xmlName);if (!file.open(QIODevice::WriteOnly | QIODevice::Truncate |QIODevice::Text))return false;QDomDocument doc;QDomProcessin…

损失函数篇 | YOLOv10 更换损失函数之 SIoU / EIoU / WIoU / Focal_xIoU 最全汇总版

文章目录 更换方式CIoUDIoUEIoUGIoUSIoUWIoUFocal_CIoUFocal_DIoUFocal_EIoUFocal_GIoUFocal_SIoU提示更换方式 第一步:将ultralytics/ultralytics/utils/metrics.py文件中的bbox_iou替换为如下的代码:class WIoU_Scale: if monotonous = None , v1if monotonous = True , v…

通过台达ASDA-Soft伺服调试软件导入和导出伺服参数的具体方法示例

通过台达ASDA-Soft伺服调试软件导入和导出伺服参数的具体方法示例 首先,找一根通讯线,如下图所示,打印机通讯线就可以, 通信线连接台达伺服驱动器和电脑后,打开ASDA-Soft软件,如下图所示,勾选On-Line,然后点击开始自动侦测, 如下图所示,正常情况下,软件可以自动侦测…

国产长芯微LDC5541/LDC5542数模转换芯片DAC完全P2P替代AD5541/AD5542

LDC5541/LDC5542是单16位串行输入电压输出数模转换器(DAC),工作电压为2.7V至5.5V。DAC输出范围从0V延伸到VREF。DAC经过校准,在室温下提供16位的2LSB INL精度,在-40℃至85℃/105℃的整个指定温度范围内提供6LSB INL精度…

【PRISMA卫星有关简介】

PRISMA卫星是一颗小型超光谱成像卫星,以下是对其的详细介绍: 一、基本信息 英文全称:Prototype Research Instruments and Space Mission technology Advancement Main,或简化为PRISMA。发射时间:PRISMA卫星于2019年…

ArduSub程序学习(11)--EKF实现逻辑④

1.controlFilterModes() controlFilterModes() 是 NavEKF2_core 类中的一个关键函数,用于控制和管理扩展卡尔曼滤波器(EKF)的不同工作模式。该函数在 UpdateFilter 方法中被调用,确保滤波器根据系统状态(如飞行状态、…

如何快速建立自己的异地互联的远程视频监控系统,通过web浏览器可以直接查看公网上的监控视频(上)

目录 一、需求 二、方案 2.1、计划方案 2.2、实施准备 2.2.1所需配置的产品和服务 2.2.1.1云主机 (1)选择云平台 (2)配置云服务器 2.2.2.2视频监控平台软件 (1)视频监控平台软件 (2&am…

Gromacs位置限制问题

Atom index n in position_restraints out of bounds A common problem is placing position restraint files for multiple molecules out of order.(一个常见的问题是无序放置多个分子的位置约束文件。)Recall that a position restraint itp (page 449) file containing a …

08_OpenCV文字图片绘制

import cv2 import numpy as npimg cv2.imread(image0.jpg,1) font cv2.FONT_HERSHEY_SIMPLEXcv2.rectangle(img,(500,400),(200,100),(0,255,0),20) # 1 dst 2 文字内容 3 坐标 4 5 字体大小 6 color 7 粗细 8 line type cv2.putText(img,flower,(200,50),font,1,(0,0,250)…

今日早报 每日精选15条新闻简报 每天一分钟 知晓天下事 9月30日,星期一

每天一分钟,知晓天下事! 2024年9月30日 星期一 农历八月廿八 1、 央行:首套、二套房存量房贷利率批量下调,平均降幅0.5%左右;取消个人房贷重定价周期最短1年限制。 2、 住建部:对商品房建设严控增量、优化…

FPGA实现PCIE视频采集转SDI输出,基于GTX+XDMA中断架构,提供2套工程源码和技术支持

目录 1、前言工程概述免责声明 2、相关方案推荐我已有的PCIE方案本博已有的 SDI 编解码方案 3、PCIE基础知识扫描4、工程详细设计方案工程设计原理框图电脑端视频QT上位机XDMA配置及使用XDMA中断模块FDMA图像缓存SDI视频编码之-->RGB转BT1120SDI视频编码之-->SMPTE SD/HD…

【C语言指南】数据类型详解(上)——内置类型

💓 博客主页:倔强的石头的CSDN主页 📝Gitee主页:倔强的石头的gitee主页 ⏩ 文章专栏:《C语言指南》 期待您的关注 目录 引言 1. 整型(Integer Types) 2. 浮点型(Floating-Point …

atop系统监控工具

atop命令可以看作是top命令的增强版,它可以显示更详细的进程信息,如进程的CPU使用率、进程的内存使用率、进程的I/O使用率、网络使用率等;提供更丰富的统计信息及更灵活的配置,可以通过参数来控制显示内容和行为。 1、top和atop对…

x-cmd pkg | tokei - 代码统计利器,助你快速了解项目进度

目录 简介首次用户技术特点竞品和相关项目进一步阅读 简介 tokei 是一个使用 Rust 编写的显示有关代码统计信息的命令行工具,可以分门别类的统计目录内的代码行数。 tokei 具有良好的跨平台性,可以在 Linux、macOS、Windows 等多种平台上安装运行。 首…

国产长芯微LDC8411数模转换芯片DAC完全P2P替代DAC8411

LDC8411(16位)器件是低功耗、单通道、电压输出数模转换器(DAC)。它们提供了出色的线性度,并最大限度地减少了不希望的码间瞬态电压,同时在引脚兼容系列中提供了一条简单的升级路径。所有设备都使用一个多功…

ubuntu切换源方式记录(清华源、中科大源、阿里源)

文章目录 前言一、中科大源二、清华源三、阿里源 前言 记录ubunut切换各个源的方式。 备注:更换源之后使用sudo apt-get update更新索引。 提示:以下是本篇文章正文内容,下面案例可供参考 一、中科大源 地址:https://mirrors.u…

Shell入门基础学习笔记

目录 第1章 Shell概述 第2章 Shell解析器 第3章 Shell脚本入门 第4章 Shell中的变量 4.1 系统变量 4.2 自定义变量 4.3 特殊变量:$n 4.4 特殊变量:$# 4.5 特殊变量:$*、$ 4.6 特殊变量:$? 第5章 运算符 …

4.模拟电子技术笔记——半导体三极管

写在前面 这个是第四个模电笔记,我们讲半导体三极管 这一章的很多概念都很重要,并且有一些需要记忆的内容,要认真对待 笔记部分 1.半导体三极管的基本原理简述 1.1结构: 1.这个箭头是PN结正向导通方向 2.有两个类型&#xf…