使用CAMEL创建第一个Agent Society

笔记哥 / 04-16 / 45点赞 / 0评论 / 859阅读
## CAMEL介绍 🐫 CAMEL 是一个开源社区,致力于探索代理的扩展规律。相信,在大规模研究这些代理可以提供对其行为、能力和潜在风险的宝贵见解。为了促进这一领域的研究,实现了并支持各种类型的代理、任务、提示、模型和模拟环境。 GitHub地址:![](https://cdn.res.knowhub.vip/c/2504/16/7e010a8c?CxCAaHR0cHM6Ly9naXRodWIuY29tL2NhbWVsLWFpL2NhbWVsAw%3d%3d) ![image-20250416144111937](https://cdn.res.knowhub.vip/c/2504/16/cb77fa24.png?G1YAAMTydJz4d%2f6EbqMO3yaKRJsBiSyCSgnr9fz%2fPpfI%2bzkUFu%2fZx%2fLz4S99LJeMWmEqUFANwaeSaAqSDJabllYz454O) ## 创建第一个代理社会 Society模块是 CAMEL 的核心模块之一。通过模拟信息交换过程,该模块研究代理之间的社会行为。 RolePlaying是 CAMEL 的一个独特的协作代理框架。通过这个框架,CAMEL 中的代理克服了诸如角色转换、助手重复指令、敷衍的回答、消息无限循环以及对话终止条件等众多挑战。 现在就来使用CAMEL 创建一个Agent Society。 编写.env如下所示: ```csharp Silicon_Model_ID="Qwen/Qwen2.5-72B-Instruct" ZHIPU_Model_ID="THUDM/GLM-4-32B-0414" SiliconCloud_API_KEY="你的api key" SiliconCloud_Base_URL="https://api.siliconflow.cn/v1" ``` 想要使用两个不同的模型: ```csharp from camel.societies import RolePlaying from camel.agents import ChatAgent from camel.models import ModelFactory from camel.types import ModelPlatformType import pathlib import os from dotenv import load_dotenv sys_msg = 'You are a curious stone wondering about the universe.' base_dir = pathlib.Path(__file__).parent.parent env_path = base_dir / ".env" load_dotenv(dotenv_path=str(env_path)) modeltype = os.getenv("Silicon_Model_ID") modeltype2= os.getenv("ZHIPU_Model_ID") api_key = os.getenv("SiliconCloud_API_KEY") base_url = os.getenv("SiliconCloud_Base_URL") siliconcloud_model = ModelFactory.create( model_platform=ModelPlatformType.OPENAI_COMPATIBLE_MODEL, model_type=modeltype, api_key=api_key, url=base_url, model_config_dict={"temperature": 0.4, "max_tokens": 4096}, ) siliconcloud_model2 = ModelFactory.create( model_platform=ModelPlatformType.OPENAI_COMPATIBLE_MODEL, model_type=modeltype2, api_key=api_key, url=base_url, model_config_dict={"temperature": 0.4, "max_tokens": 4096}, ) ``` 设置任务、AI用户、AI助手参数: ```csharp task_kwargs = { 'task_prompt': '制定一个新人小白学习esp32的教程,使用中文回答。', 'with_task_specify': True, 'task_specify_agent_kwargs': {'model': siliconcloud_model} } user_role_kwargs = { 'user_role_name': '一个esp32小白', 'user_agent_kwargs': {'model': siliconcloud_model} } assistant_role_kwargs = { 'assistant_role_name': '一个esp32专家', 'assistant_agent_kwargs': {'model': siliconcloud_model2} } ``` 构建社会: ```csharp society = RolePlaying( **task_kwargs, # The task arguments **user_role_kwargs, # The instruction sender's arguments **assistant_role_kwargs, # The instruction receiver's arguments ) ``` 让这个社会最多运行10轮: ```csharp def is_terminated(response): """ Give alerts when the session should be terminated. """ if response.terminated: role = response.msg.role_type.name reason = response.info['termination_reasons'] print(f'AI {role} terminated due to {reason}') return response.terminated def run(society, round_limit: int=10): # Get the initial message from the ai assistant to the ai user input_msg = society.init_chat() # Starting the interactive session for _ in range(round_limit): # Get the both responses for this round assistant_response, user_response = society.step(input_msg) # Check the termination condition if is_terminated(assistant_response) or is_terminated(user_response): break # Get the results print(f'[AI User] {user_response.msg.content}.\n') # Check if the task is end if 'CAMEL_TASK_DONE' in user_response.msg.content: break print(f'[AI Assistant] {assistant_response.msg.content}.\n') # Get the input message for the next round input_msg = assistant_response.msg return None if __name__ == "__main__": run(society, round_limit=10) ``` 查看效果。 第一轮: ![image-20250416145503193](https://cdn.res.knowhub.vip/c/2504/16/0dbd004f.png?G1cAAMTsdJxIvIi026hD2jvFHc2ARRpBpYT1es9Z%2byb6fgdD4jNan74%2f%2fKb16ZRhBmECo7AghKSpCKOIXiEZVGsWq3ENBw%3d%3d) 第二轮: ![image-20250416145611095](https://cdn.res.knowhub.vip/c/2504/16/fe3acb5c.png?G1cAAER17rxgpWwKfice0wSBBJsBizSCSgnr9fz%2f2pfI%2bzlBjfdoffr%2b8JvWp0tmKVQIQYMihHQkU9BAC6memkFUjWs4) AI用户会重新问一个与解决任务相关的问题。 第三轮: ![image-20250416145711816](https://cdn.res.knowhub.vip/c/2504/16/7c5495f3.png?G1cAAETn9LwUKLDovtMdbIlTE20GLNIIKiWs13vO2jfR9wcYlp%2fR%2boz94TetzyBFKTAmMJwNKcglbgx34STQCq1aPa8R) 第四轮: ![image-20250416145741388](https://cdn.res.knowhub.vip/c/2504/16/626cc408.png?G1cAAETn9LwU6MDgvtMdbIlTE20GLNIIKiWs13vO2jfR9wcYmp%2fR%2boz94Tetz6AL7lAmMIwVKUgRU4ap1yRVHZWLIK8R) 第五轮: ![image-20250416145817329](https://cdn.res.knowhub.vip/c/2504/16/f475fd50.png?G1YAAMR0rnGCXj8hbiMO1QSBBJoBiSyCSgnr9Z6z9k30%2fSEQy89ofcb%2b8JfWZ5BKrWIggTgMyfPFbhB3RWIUVy6l5jUC) 第六轮: ![image-20250416145850761](https://cdn.res.knowhub.vip/c/2504/16/403b2945.png?G1YAAMTsdJxI8gm026hD2jvFHc2ARBZBpYT1es9Z%2byb6fgfD4jNan74%2f%2fKX16aSoFcYERmJD8JIlGSMV0WAXauaiFtdw) 第7轮: ![image-20250416145948076](https://cdn.res.knowhub.vip/c/2504/16/274a2fb4.png?G1cAAER17rxgo3aAfice0wSBBJsBizSCSgnr9fz%2f2pfI%2bzkUjPdoffr%2b8JvWp8uBWkEVKEyJEFJORoUVMiQWPXMlLa7h) 当达到令牌限制时,为了满足限制,将从记忆中删除部分消息。 如果10轮还没完成的话会直接结束: ![image-20250416150311278](https://cdn.res.knowhub.vip/c/2504/16/a451aede.png?G1cAAETn9LwUqDDJvtMdbIlTE20GLNIIKiWs13vO2jfR9wcYmp%2fR%2boz94Tetz6ACdygTGMaKFOQSU4apeJKiVtWtel4jAA%3d%3d) 构建这个Agent Society有什么用呢? 我觉得一个很有用的点就是适合头脑风暴场景,有一个问题或者方案需要详细讨论,那就丢给两个或更多的AI,让它们进行详细讨论,我们先看一下它们的讨论情况,看看是否有一些有效的建议,看看能不能找到一些灵感。 如果觉得在控制台中不好看,可以将结果写入文件中: ```csharp def run(society, round_limit: int=10): # Get the initial message from the ai assistant to the ai user input_msg = society.init_chat() # Starting the interactive session for _ in range(round_limit): # Get the both responses for this round assistant_response, user_response = society.step(input_msg) # Check the termination condition if is_terminated(assistant_response) or is_terminated(user_response): break # Get the results print(f'[AI User] {user_response.msg.content}.\n') # 写入一个md文件 with open('output.md', 'a', encoding='utf-8') as f: f.write(f'[AI User] {user_response.msg.content}.\n') # Check if the task is end if 'CAMEL_TASK_DONE' in user_response.msg.content: break print(f'[AI Assistant] {assistant_response.msg.content}.\n') # 写入一个md文件 with open('output.md', 'a', encoding='utf-8') as f: f.write(f'[AI Assistant] {assistant_response.msg.content}.\n') # Get the input message for the next round input_msg = assistant_response.msg return None ``` 对于这个任务、AI用户、AI助手参数: ```csharp task_kwargs = { 'task_prompt': '制定一个新人小白学习C#的教程,使用中文回答。', 'with_task_specify': True, 'task_specify_agent_kwargs': {'model': siliconcloud_model} } user_role_kwargs = { 'user_role_name': '一个想要学习C#小白', 'user_agent_kwargs': {'model': siliconcloud_model} } assistant_role_kwargs = { 'assistant_role_name': '一个C#专家', 'assistant_agent_kwargs': {'model': siliconcloud_model2} } ``` 写入到output.md文件的内容如下所示: ![image-20250416152134298](https://cdn.res.knowhub.vip/c/2504/16/d53b6a69.png?G1YAAMT0bJxoe1rENvqh%2f4lHQjMgkUVQKWG93nv3aUTf72BofGYfy8%2bHv%2fSxnBJqhTKBYawIXrKYMqykFLKKASgW93Q%3d) 相对于自己一次一次与AI交互,有些时候自己定义一些角色,让它们自己去交互,我们只看它们的结果,还是更高效一些的。