基于CAMEL 的Workforce 實現多智能體協同工作系統

文章目錄

    • 一、workforce 簡介
      • 1.架構設計
      • 2.通信機制
    • 二、workforce 工作流程圖示例
      • 1.用戶角色
      • 2.工作流程
    • 三、workforce 中重要函數說明
      • 1.`__init__`函數
      • 2.`add_single_agent_worker` 函數
      • 3.`add_role_playing_worker` 函數
      • 4.`add_workforce` 函數
    • 四、基于workforce實現多智能體協調
      • (1)創建一個 Workforce 實例
      • (2)worker定義
      • (3)添加到Workforce 的工作節點
      • (4)創建一個任務
      • (5)啟動 Workforce 的任務處理流程
      • 完整示例代碼
    • 五、遇到問題

一、workforce 簡介

Workforce是CAMEL框架中的一個多智能體協同工作系統。它以一種簡潔的方式讓多個智能體協作完成任務,類似于一個高效的團隊合作系統。

1.架構設計

Workforce采用層級架構設計。一個workforce可以包含多個工作節點(worker nodes),每個工作節點可以包含一個或多個智能體作為工作者。工作節點由workforce內部的**協調智能體(coordinator agent)**管理,協調智能體根據工作節點的描述及其工具集來分配任務。

2.通信機制

Workforce內部的通信基于任務通道(task channel)。Workforce初始化時會創建一個所有節點共享的通道。任務會被發布到這個通道中,每個工作節點會監聽通道,接受分配給它的任務并解決。當任務完成后,工作節點會將結果發布回通道,結果會作為其他任務的"依賴項"保留在通道中,供所有工作節點共享。

通過這種機制,workforce能夠以協作和高效的方式解決任務。

二、workforce 工作流程圖示例

如圖,展示了如何通過以下智能體協作完成一個請求,即“創建一個產品的登錄頁面”

在這里插入圖片描述

1.用戶角色

  • Root Node (Manager):作為系統的管理者,負責接收任務并協調任務的分解和分配。

  • Coordinator Agent (協調智能體)Task Manager Agent (任務管理智能體):管理任務分解、依賴關系、分發任務,以及監控任務完成情況。

  • Leaf Nodes (Workers):執行任務的實際智能體,分別承擔不同的角色(如“內容撰寫者”和“代碼撰寫者”)。

2.工作流程

(a) 用戶需求的接收

用戶發出任務請求(例如“創建一個登錄頁面”,圖中 1)。

Coordinator Agent 接收需求,作為入口點。

(b) 任務分解與定義

Coordinator Agent 通過任務分解策略,將請求拆分為多個子任務(如任務 A.1 和 A.2),并定義:

這些任務被送到 Task Manager Agent 進行分發(圖中 2 和 3)。

? 任務的分配

Task Manager Agent 將任務分發到 Channel(圖中 4),這是一個任務管理中樞。

任務按角色需求分配到 Leaf Nodes (Workers),包括:

(d) Leaf Nodes 執行任務

內容撰寫者 (Content Writer)

代碼撰寫者 (Code Writer)

(e) 結果整合與返回

Coordinator Agent 匯總所有任務結果(如 A.1 和 A.2 的結果)。

將完整的任務結果返回給用戶(圖中 18)。

三、workforce 中重要函數說明

1.__init__函數

    def __init__(self,description: str,children: Optional[List[BaseNode]] = None,coordinator_agent_kwargs: Optional[Dict] = None,task_agent_kwargs: Optional[Dict] = None,new_worker_agent_kwargs: Optional[Dict] = None,) -> None:super().__init__(description)self._child_listening_tasks: Deque[asyncio.Task] = deque()self._children = children or []self.new_worker_agent_kwargs = new_worker_agent_kwargscoord_agent_sys_msg = BaseMessage.make_assistant_message(role_name="Workforce Manager",content="You are coordinating a group of workers. A worker can be ""a group of agents or a single agent. Each worker is ""created to solve a specific kind of task. Your job ""includes assigning tasks to a existing worker, creating ""a new worker for a task, etc.",)self.coordinator_agent = ChatAgent(coord_agent_sys_msg, **(coordinator_agent_kwargs or {}))task_sys_msg = BaseMessage.make_assistant_message(role_name="Task Planner",content="You are going to compose and decompose tasks.",)self.task_agent = ChatAgent(task_sys_msg, **(task_agent_kwargs or {}))# If there is one, will set by the workforce class wrapping thisself._task: Optional[Task] = Noneself._pending_tasks: Deque[Task] = deque()

其中coordinator_agent的本質為ChatAgent,role_name=“Workforce Manager”,對應的提示詞為:

"You are coordinating a group of workers. A worker can be ""a group of agents or a single agent. Each worker is ""created to solve a specific kind of task. Your job ""includes assigning tasks to a existing worker, creating ""a new worker for a task, etc."

task_agentt的本質也是ChatAgent,role_name=“Task Planner”,對應的提示詞為:

"You are going to compose and decompose tasks."

2.add_single_agent_worker 函數

    @check_if_running(False)def add_single_agent_worker(self, description: str, worker: ChatAgent) -> Workforce:r"""Add a worker node to the workforce that uses a single agent.Args:description (str): Description of the worker node.worker (ChatAgent): The agent to be added.Returns:Workforce: The workforce node itself."""worker_node = SingleAgentWorker(description, worker)self._children.append(worker_node)return self

調用add_single_agent_worker時會添加單個工作節點worker_node.

3.add_role_playing_worker 函數

    def add_role_playing_worker(self,description: str,assistant_role_name: str,user_role_name: str,assistant_agent_kwargs: Optional[Dict] = None,user_agent_kwargs: Optional[Dict] = None,chat_turn_limit: int = 3,) -> Workforce:r"""Add a worker node to the workforce that uses `RolePlaying` system.Args:description (str): Description of the node.assistant_role_name (str): The role name of the assistant agent.user_role_name (str): The role name of the user agent.assistant_agent_kwargs (Optional[Dict], optional): The keywordarguments to initialize the assistant agent in the roleplaying, like the model name, etc. Defaults to `None`.user_agent_kwargs (Optional[Dict], optional): The keyword argumentsto initialize the user agent in the role playing, like themodel name, etc. Defaults to `None`.chat_turn_limit (int, optional): The maximum number of chat turnsin the role playing. Defaults to 3.Returns:Workforce: The workforce node itself."""worker_node = RolePlayingWorker(description,assistant_role_name,user_role_name,assistant_agent_kwargs,user_agent_kwargs,chat_turn_limit,)self._children.append(worker_node)return self

調用add_role_playing_worker時會添加RolePlayingWorker的工作節點.

4.add_workforce 函數

	@check_if_running(False)def add_workforce(self, workforce: Workforce) -> Workforce:r"""Add a workforce node to the workforce.Args:workforce (Workforce): The workforce node to be added.Returns:Workforce: The workforce node itself."""self._children.append(workforce)return self

調用add_workforce時會添加workforce類型的工作節點.

四、基于workforce實現多智能體協調

關鍵步驟為

(1)創建一個 Workforce 實例

workforce = Workforce(description="旅游攻略制作與評估工作組",new_worker_agent_kwargs={'model':model},coordinator_agent_kwargs={'model':model},task_agent_kwargs={'model':model})

(2)worker定義

planner_agent = ChatAgent(system_message="""你是一個專業的旅行規劃師。你的職責是:1. 根據景點分布規劃合理的游覽順序2. 為每天安排適量的景點和活動3. 考慮用餐、休息等時間4. 注意不同季節的特點請確保行程安排合理且具有可行性。""",model=model,output_language='中文')

(3)添加到Workforce 的工作節點

workforce.add_single_agent_worker("負責制定詳細行程規劃",worker=planner_agent
)

(4)創建一個任務

from camel.tasks import Task# 創建一個用于測試的任務
task = Task(content="規劃一個3天的巴黎旅行計劃。",id="0",  # id可以是任何標記字符串
)

(5)啟動 Workforce 的任務處理流程

task = workforce.process_task(task)

完整示例代碼

from camel.agents import ChatAgent
from camel.models import ModelFactory
from camel.types import ModelPlatformType
from camel.messages import BaseMessage
from camel.societies.workforce import Workforce
from camel.toolkits import SearchToolkit
from camel.tasks import Task
from camel.toolkits import FunctionTool
from camel.configs import SiliconFlowConfig  # 關鍵from dotenv import load_dotenv
import osload_dotenv()api_key = os.getenv('Siliconflow_API_KEY')model = ModelFactory.create(model_platform=ModelPlatformType.SILICONFLOW,model_type="Qwen/Qwen2.5-72B-Instruct",model_config_dict=SiliconFlowConfig(temperature=0.2).as_dict(),api_key=api_key
)# 創建一個 Workforce 實例
workforce = Workforce(description="旅游攻略制作與評估工作組",new_worker_agent_kwargs={'model':model},coordinator_agent_kwargs={'model':model},task_agent_kwargs={'model':model})search_tool = FunctionTool(SearchToolkit().search_duckduckgo)search_agent = ChatAgent(system_message="""你是一個專業的旅游信息搜索助手。你的職責是:1. 搜索目的地的主要景點信息2. 搜索當地特色美食信息3. 搜索交通和住宿相關信息請確保信息的準確性和實用性。""",model=model,tools=[search_tool],output_language='中文')planner_agent = ChatAgent(system_message="""你是一個專業的旅行規劃師。你的職責是:1. 根據景點分布規劃合理的游覽順序2. 為每天安排適量的景點和活動3. 考慮用餐、休息等時間4. 注意不同季節的特點請確保行程安排合理且具有可行性。""",model=model,output_language='中文')reviewer_agent = ChatAgent(system_message="""你是一個經驗豐富的旅行愛好者。你的職責是:1. 從游客角度評估行程的合理性2. 指出可能的問題和改進建議3. 補充實用的旅行小貼士4. 評估行程的性價比請基于實際旅行經驗給出中肯的建議。""",model=model,output_language='中文'
)# 添加工作節點
workforce.add_single_agent_worker("負責搜索目的地相關信息",worker=search_agent
).add_single_agent_worker("負責制定詳細行程規劃",worker=planner_agent
).add_single_agent_worker("負責從游客角度評估行程",worker=reviewer_agent
)from camel.tasks import Task# 創建一個用于測試的任務
task = Task(content="規劃一個3天的巴黎旅行計劃。",id="0",  # id可以是任何標記字符串
)task = workforce.process_task(task)print(task.result)

五、遇到問題

關鍵報錯代碼

If you have a specific format in mind or a particular context for this number, please let me know!
Traceback (most recent call last):File "/home/allyoung/camel_course/03-2-33-Workforce.py", line 84, in <module>task = workforce.process_task(task)File "/home/allyoung/camel/camel/societies/workforce/utils.py", line 69, in wrapperreturn func(self, *args, **kwargs)File "/home/allyoung/camel/camel/societies/workforce/workforce.py", line 153, in process_taskasyncio.run(self.start())File "/home/allyoung/anaconda3/envs/python310/lib/python3.10/asyncio/runners.py", line 44, in runreturn loop.run_until_complete(main)File "/home/allyoung/anaconda3/envs/python310/lib/python3.10/asyncio/base_events.py", line 641, in run_until_completereturn future.result()File "/home/allyoung/camel/camel/societies/workforce/workforce.py", line 469, in startawait self._listen_to_channel()File "/home/allyoung/camel/camel/societies/workforce/workforce.py", line 437, in _listen_to_channelawait self._post_ready_tasks()File "/home/allyoung/camel/camel/societies/workforce/workforce.py", line 402, in _post_ready_tasksassignee_id = self._find_assignee(task=ready_task)File "/home/allyoung/camel/camel/societies/workforce/workforce.py", line 288, in _find_assigneeresult_dict = json.loads(response.msg.content)File "/home/allyoung/anaconda3/envs/python310/lib/python3.10/json/__init__.py", line 346, in loadsreturn _default_decoder.decode(s)File "/home/allyoung/anaconda3/envs/python310/lib/python3.10/json/decoder.py", line 337, in decodeobj, end = self.raw_decode(s, idx=_w(s, 0).end())File "/home/allyoung/anaconda3/envs/python310/lib/python3.10/json/decoder.py", line 355, in raw_decoderaise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/diannao/74155.shtml
繁體地址,請注明出處:http://hk.pswp.cn/diannao/74155.shtml
英文地址,請注明出處:http://en.pswp.cn/diannao/74155.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

每日一題力扣2974.最小數字游戲c++

2974. 最小數字游戲 - 力扣&#xff08;LeetCode&#xff09; class Solution { public:vector<int> numberGame(vector<int>& nums) {vector<int> arr(nums.size());sort(nums.begin(),nums.end());for(size_t i0;i<nums.size();i2){arr[i]nums[i1]…

對接馬來西亞、印度、韓國、越南等全球金融數據示例

Python對接StockTV全球金融數據API的封裝實現及使用教程&#xff1a; import requests import websockets import asyncio from typing import Dict, List, Optional, Union from datetime import datetimeclass StockTVClient:"""StockTV全球金融數據API客戶端…

Adobe After Effects 操作

Adobe After Effects &#xff08;AE&#xff09;可以實現將多個元素進行合成&#xff0c;實現特殊效果。AE的項目文件是aep&#xff0c;可以將素材、層、效果等一切信息&#xff0c;保存在這個項目文件中。 AE的原理&#xff0c;和PS的原理非常類似。 操作界面 操作界面如…

【React】基于自定義Hook提取公共邏輯

目錄 自定義Hook自定義Hook 1自定義Hook 2使用 注意事項 自定義Hook 作用&#xff1a;提取封裝一些公共的處理邏輯 玩法&#xff1a;創建一個函數&#xff0c;名字需要是 useXxx &#xff0c;后期就可以在組件中調用這個方法&#xff01; 自定義Hook 1 頁面加載的時候修改瀏…

AUTOSAR與arxml的文檔解析

如下是文檔腦圖 一、文檔概述 該文檔是 AUTOSAR 經典平臺的應用接口用戶指南&#xff0c;主要解釋 **Al Table&#xff08;應用接口表&#xff09;** 的結構、方法論及相關技術細節&#xff0c;幫助開發者理解如何通過標準化接口實現軟件組件的互操作性。 關鍵內容 目的&#…

油候插件、idea、VsCode插件推薦(自用)

開發軟件&#xff1a; 之前的文章&#xff1a; 開發必裝最實用工具軟件與網站 推薦一下我使用的開發工具 目前在用的 油候插件 AC-baidu-重定向優化百度搜狗谷歌必應搜索_favicon_雙列 讓查詢變成多列&#xff0c;而且可以流式翻頁 Github 增強 - 高速下載 github下載 TimerHo…

阿里云平臺服務器操作以及發布靜態項目

目錄&#xff1a; 1、云服務器介紹2、云服務器界面3、發布靜態項目1、啟動nginx2、ngixn訪問3、外網訪問測試4、拷貝靜態資源到nginx目錄下并重啟nginx 1、云服務器介紹 2、云服務器界面 實例詳情&#xff1a;里面主要顯示云服務的內外網地址以及一些啟動/停止的操作。監控&…

Spring Cache 實戰指南

redis中常見的問題 前言 在本文中&#xff0c;我們將探討 Redis 在緩存中的應用&#xff0c;并解決一些常見的緩存問題。為了簡化理解&#xff0c;本文中的一些配置是直接寫死的&#xff0c;實際項目中建議將這些配置寫入配置文件&#xff0c;并通過配置文件讀取。 一、為什…

區塊鏈開發技術公司:引領數字經濟的創新力量

在數字化浪潮席卷全球的今天&#xff0c;區塊鏈技術作為新興技術的代表&#xff0c;正以其獨特的去中心化、不可篡改和透明性等特點&#xff0c;深刻改變著各行各業的發展格局。區塊鏈開發技術公司&#xff0c;作為這一領域的先鋒和推動者&#xff0c;正不斷研發創新&#xff0…

EJS緩存解決多頁面相同閃動問題

基于 EJS 的模板引擎特性及其緩存機制&#xff0c;以下是關于緩存相同模塊的詳細解答&#xff1a; 一、EJS 緩存機制的核心能力 模板編譯緩存 EJS 默認會將編譯后的模板函數緩存在內存中&#xff0c;當相同模板文件被多次渲染時&#xff0c;會直接復用已編譯的模板函數&#x…

多條件排序(C# and Lua)

C# 升序排序 OrderBy 按升序對序列的元素進行排序 ThenBy 按升序對序列中的元素執行后續排序 降序排序 OrderByDescending 按降序對序列的元素排序 ThenByDescending 按降序對序列中的元素執行后續排序 public class Fruit {public int id;public string name;publi…

React19源碼系列之Hooks(useId)

useId的介紹 https://zh-hans.react.dev/reference/react/useId useId 是 React 18 引入的一個新 Hook&#xff0c;主要用于生成全局唯一的 ID。在開發中&#xff0c;我們經常需要為元素&#xff08;如表單元素、模態框等&#xff09;生成唯一 ID&#xff0c;以便在 JavaScri…

經典面試題:C/C++中static關鍵字的三大核心作用與實戰應用

一、修飾局部變量&#xff1a;改變生命周期&#xff0c;保留跨調用狀態 核心作用&#xff1a; ?延長生命周期&#xff1a;將局部變量從棧區移至靜態存儲區&#xff08;數據段或BSS段&#xff09;&#xff0c;生命周期與程序一致?保留狀態&#xff1a;變量在函數多次調用間保…

Redisson 分布式鎖原理

加鎖原理 # 如果鎖不存在 if (redis.call(exists, KEYS[1]) 0) then# hash結構,鎖名稱為key,線程唯一標識為itemKey&#xff0c;itemValue為一個計數器。支持相同客戶端線程可重入,每次加鎖計數器1.redis.call(hincrby, KEYS[1], ARGV[2], 1);# 設置過期時間redis.call(pexpi…

【數據結構】棧與隊列:基礎 + 競賽高頻算法實操(含代碼實現)

什么是棧&#xff1f;什么是隊列&#xff1f; 什么是先進后出&#xff1f;什么是先進先出&#xff1f; 了解基礎之后&#xff0c;又如何用來寫算法題&#xff1f; 帶著這些疑問&#xff0c;讓我帶領你&#xff0c;走進棧與隊列的世界 棧與隊列 棧&#xff1a; 1、棧的基本…

單元化架構在字節跳動的落地實踐

資料來源&#xff1a;火山引擎-開發者社區 什么是單元化 單元化的核心理念是將業務按照某種維度劃分成一個個單元&#xff0c; 理想情況下每個單元內部都是完成所有業務操作的自包含集合&#xff0c;能獨立處理業務流程&#xff0c;各個單元均有其中一部分數據&#xff0c;所有…

基于Python的垃圾短信分類

垃圾短信分類 1 垃圾短信分類問題介紹 1.1 垃圾短信 隨著移動互聯科技的高速發展&#xff0c;信息技術在不斷改變著我們的生活&#xff0c;讓我們的生活更方便&#xff0c;其中移動通信技術己經在我們生活起到至關重要的作用&#xff0c;與我們每個人人息息相關。短信作為移…

leetcode1971.尋找圖中是否存在路徑

初嘗并查集&#xff0c;直接套用模板 class Solution { private:vector<int> father;void init() {for(int i0;i<father.size();i)father[i]i;}int find(int v) {return vfather[v]?v:father[v]find(father[v]);//路徑壓縮}bool isSame(int u,int v){ufind(u);vfind…

QAI AppBuilder 快速上手(7):目標檢測應用實例

YOLOv8_det是YOLO 系列目標檢測模型&#xff0c;專為高效、準確地檢測圖像中的物體而設計。該模型通過引入新的功能和改進點&#xff0c;如因式分解卷積&#xff08;factorized convolutions&#xff09;和批量歸一化&#xff08;batch normalization&#xff09;&#xff0c;在…

景聯文科技:以高質量數據標注推動人工智能領域創新與發展

在當今這個由數據驅動的時代&#xff0c;高質量的數據標注對于推動機器學習、自然語言處理&#xff08;NLP&#xff09;、計算機視覺等領域的發展具有不可替代的重要性。數據標注過程涉及對原始數據進行加工&#xff0c;通過標注特定對象的特征來生成能夠被機器學習模型識別和使…