AgentSociety 2完全指南:如何构建LLM原生智能体仿真环境
AgentSociety 2完全指南:如何构建LLM原生智能体仿真环境
【免费下载链接】agentsocietyAgentSociety 2 is a modern, LLM-native agent simulation platform designed for social science research and experimental design. It provides a flexible framework for creating and managing intelligent agents in simulated environments.项目地址: https://gitcode.com/gh_mirrors/ag/agentsociety
AgentSociety 2 是一个现代化的LLM原生智能体仿真平台,专为社会科学研究和实验设计打造。它提供了灵活的框架,用于在模拟环境中创建和管理智能体,帮助研究人员探索复杂的社会行为和互动模式。
为什么选择AgentSociety 2?
AgentSociety 2 作为LLM原生的智能体仿真平台,具有以下核心优势:
- LLM驱动的智能体:智能体行为完全由大型语言模型驱动,能够展现复杂的认知和决策能力
- 高度可扩展架构:支持从少量智能体到大规模仿真的平滑扩展
- 灵活的环境设计:可定制的环境模块,适应不同研究需求
- 完整的实验工具链:从设计、运行到分析的全流程支持
- 可复现的研究结果:详细的追踪和回放系统,确保实验结果可验证
AgentSociety 2的整体架构设计,展示了智能体、环境和服务之间的交互关系
快速安装AgentSociety 2
系统要求
AgentSociety 2 需要 Python 3.11 或更高版本。在开始前,请确保您的系统满足这一要求。
安装方式
从PyPI安装(推荐)
最简单的安装方法是使用pip:
pip install agentsociety2如需安装开发依赖:
pip install "agentsociety2[dev]"从源码安装
如果需要最新开发版本,可以从源码安装:
git clone https://gitcode.com/gh_mirrors/ag/agentsociety cd agentsociety/packages/agentsociety2 pip install -e .验证安装
安装完成后,运行以下代码验证:
import agentsociety2 print(agentsociety2.__version__)您应该能看到版本号被打印出来,表明安装成功。
配置LLM环境
AgentSociety 2 需要配置LLM API凭证才能正常工作。以下是基本配置步骤:
环境变量配置
设置必要的环境变量:
# 默认LLM配置(必需) export AGENTSOCIETY_LLM_API_KEY="your-api-key" export AGENTSOCIETY_LLM_API_BASE="https://api.openai.com/v1" export AGENTSOCIETY_LLM_MODEL="gpt-5.5"使用.env文件(推荐)
在项目目录中创建.env文件:
# 从仓库根目录复制模板 cp .env.example .env # 编辑.env文件填入API Key.env文件内容示例:
# 必需的LLM API配置 AGENTSOCIETY_LLM_API_KEY=your-api-key AGENTSOCIETY_LLM_API_BASE=https://api.openai.com/v1 AGENTSOCIETY_LLM_MODEL=gpt-5.5 # 可选的智能体行为配置 AGENT_MODEL=gpt-5.5 # 覆盖智能体使用的模型 AGENT_CONTEXT_WINDOW=200000 # 模型上下文窗口大小 AGENT_MAX_TOOL_ROUNDS=24 # 最大工具循环轮数高级LLM调度配置
对于大规模仿真,您可能需要调整LLM调度参数:
# 每个本地LLMClient的AIMD初始并发 export AGENTSOCIETY_LLM_RAY_CONCURRENCY=16 # 每个step_agent_batch Ray Task处理的智能体数 export AGENTSOCIETY_BATCH_SIZE=256创建您的第一个智能体仿真
下面我们将创建一个简单的多智能体仿真场景,让智能体相互介绍自己。
基本代码示例
import asyncio from datetime import datetime from pathlib import Path from agentsociety2.env import CodeGenRouter from agentsociety2.contrib.env import SimpleSocialSpace from agentsociety2.society import AgentSociety async def main(): # 1) 声明智能体元数据 agent_specs = [ {"id": i, "profile": {"name": f"Player{i}", "personality": "friendly"}, "config": {}} for i in range(1, 4) ] names = [(s["id"], s["profile"]["name"]) for s in agent_specs] # 2) 创建环境路由器 env_router = CodeGenRouter(env_modules=[SimpleSocialSpace(agent_id_name_pairs=names)]) # 3) 创建并初始化仿真社会 society = AgentSociety( agent_specs=agent_specs, agent_class_name="PersonAgent", env_router=env_router, start_t=datetime.now(), run_dir=Path("run"), ) await society.init() # 4) 让每个智能体自我介绍 for spec in agent_specs: response = await society.ask( f"Tell {spec['profile']['name']} to introduce themselves to the group!" ) print(f"{spec['profile']['name']}: {response}") await society.close() if __name__ == "__main__": asyncio.run(main())运行此代码后,您将看到类似以下的输出:
Player1: Hello everyone! I'm Player1, excited to be part of this group. I'm friendly and always up for interesting conversations. Player2: Hi everyone, I'm Player2. I'm looking forward to getting to know all of you better and having some great discussions. Player3: Greetings! I'm Player3. I'm friendly and curious about what we'll explore together. Nice to meet you all!多智能体交互的仿真结果展示
创建自定义环境模块
环境模块允许智能体与特定功能进行交互。下面是创建自定义环境的示例:
自定义环境代码
from agentsociety2.env import EnvBase, tool class MyEnvironment(EnvBase): """一个自定义环境模块,提供天气查询和心情设置功能。""" @tool(readonly=True, kind="observe") def get_weather(self, agent_id: int) -> str: """获取当前天气信息。""" return "天气晴朗,温度25°C。" @tool(readonly=False) def set_mood(self, agent_id: int, mood: str) -> str: """改变智能体的心情状态。""" return f"智能体 {agent_id} 的心情现在是 {mood}。"在仿真中使用自定义环境
# 创建环境路由器,包含自定义环境 env_router = CodeGenRouter(env_modules=[MyEnvironment()]) # 创建仿真社会时使用此环境 society = AgentSociety( agent_specs=agent_specs, agent_class_name="PersonAgent", env_router=env_router, start_t=datetime.now(), run_dir=Path("run"), )现在智能体可以使用这些工具来获取天气信息或改变自己的心情了!
使用CLI运行实验
AgentSociety 2 提供了强大的命令行界面用于运行实验,特别适合生产环境和大规模仿真。
前台运行(调试模式)
python -m agentsociety2.society.cli \ --config my_experiment/init/init_config.json \ --steps my_experiment/init/steps.yaml \ --run-dir my_experiment/run \ --log-level DEBUG后台运行(生产模式)
python -m agentsociety2.society.cli \ --config my_experiment/init/init_config.json \ --steps my_experiment/init/steps.yaml \ --run-dir my_experiment/run \ --log-level INFO \ --log-file my_experiment/run/output.log &重要提示:后台运行时必须指定
--log-file参数,以便记录实验过程。
AgentSociety 2的实验运行界面,展示了仿真过程中的关键指标
AgentSociety 2核心架构
AgentSociety 2采用了先进的分布式架构,使其能够高效处理大规模智能体仿真。
执行模型
AgentSociety 2将智能体状态存储在独立的工作区中,执行时由Ray Task按批重建和推进智能体。环境路由、LLM调度、追踪和回放等运行时组件作为共享服务存在,通过ServiceProxy注入到每个智能体。
AgentSociety 2的执行模型,展示了智能体与共享服务之间的交互
主要组件
- 智能体(Agent):基于LLM的自主实体,具有记忆和决策能力
- 环境模块(Env Modules):提供智能体可交互的环境功能
- 环境路由(Env Router):将智能体请求映射到环境模块功能
- LLM调度器:管理LLM调用,确保高效并发和资源利用
- 追踪系统(Trace):记录仿真过程中的关键事件和性能数据
- 回放系统(Replay):存储和分析仿真结果,支持结果复现
常见使用模式
只读查询
对于不修改状态的查询,使用society.ask():
# 只读查询,不会修改环境状态 response = await society.ask("当前仿真中有哪些智能体?")状态修改
对于需要修改环境的操作,使用society.intervene():
# 允许修改环境的干预操作 result = await society.intervene("让所有智能体感到开心")查询特定智能体
向特定智能体提问:
# 向特定智能体提问 response = await society.ask("Alice,你对当前情况有什么看法?")高级应用示例
AgentSociety 2可以用于各种复杂的社会科学研究。以下是一些高级应用场景:
1. 群体决策研究
模拟群体在面临共同问题时的决策过程,分析信息传播和意见形成。
2. 社会网络动态
研究信息在社交网络中的传播模式,探索谣言扩散和舆论形成机制。
3. 紧急情况下的行为模拟
如自然灾害发生时的人群疏散模拟,帮助优化应急响应策略。
飓风影响下的人群行为仿真结果可视化
总结与下一步
通过本指南,您已经了解了AgentSociety 2的基本安装、配置和使用方法。现在您可以开始创建自己的智能体仿真实验了!
推荐后续学习
- 智能体开发:深入了解如何创建自定义智能体类型
- 环境设计:学习开发复杂的环境模块和工具
- 实验设计:掌握如何设计科学的仿真实验
- 数据分析:了解如何利用追踪和回放数据进行深入分析
AgentSociety 2为社会科学研究提供了强大的工具,无论是学术研究还是政策模拟,都能帮助您探索复杂的社会现象和人类行为。
祝您好运,开始您的智能体仿真之旅吧!🚀
【免费下载链接】agentsocietyAgentSociety 2 is a modern, LLM-native agent simulation platform designed for social science research and experimental design. It provides a flexible framework for creating and managing intelligent agents in simulated environments.项目地址: https://gitcode.com/gh_mirrors/ag/agentsociety
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
