Concordia – Google DeepMind 生成式社會模擬框架完整教學

Concordia 是由 Google DeepMind 開發的開源 Python 函式庫,用於建構以大型語言模型 (Large Language Model; LLM) 驅動的多代理人 (Multi-Agent) 生成式社會模擬 (Generative Social Simulation)。它採用桌上角色扮演遊戲 (Tabletop Role-Playing Game; TRPG) 的互動模式,讓代理人以自然語言 (Natural Language) 描述行動意圖,再由遊戲主持人 (Game Master; GM) 判定行動結果與環境變化。


1. 專案概述 (Project Overview)

1.1 什麼是 Concordia?

Concordia 是一套生成式代理人基礎模型建構框架 (Generative Agent-Based Modeling Framework),核心目標是讓研究者與開發者能快速組裝、執行、分析「多個 LLM 驅動的代理人在具體物理、社會或數位環境中互動」的模擬實驗。

與傳統基於規則的代理人模擬 (Rule-Based Agent Simulation) 不同,Concordia 的代理人:

  • 使用 LLM 進行推理 (Reasoning)、決策 (Decision Making) 與自然語言產出
  • 擁有關聯式記憶體 (Associative Memory) 以儲存和檢索過往經驗
  • 透過可組合的元件 (Component) 架構定義行為邏輯

1.2 關鍵指標

指標數值
Stars1,486
Forks335
主要語言 (Primary Language)Python
授權 (License)Apache 2.0
建立日期2023-11-21
最近更新2026-06-19
PyPI 套件名稱gdm-concordia

1.3 適用場景 (Use Cases)

領域應用範例
社會科學研究 (Social Science Research)模擬社會規範 (Social Norms) 演化、合作與衝突動態
AI 安全與倫理 (AI Safety & Ethics)測試代理人在道德困境 (Moral Dilemma) 中的行為模式
認知神經科學 (Cognitive Neuroscience)模擬認知偏誤 (Cognitive Bias) 與決策歷程
經濟學 (Economics)市場動態、拍賣機制 (Auction Mechanism)、賽局理論 (Game Theory) 實驗
合成資料生成 (Synthetic Data Generation)為個人化推薦系統產生模擬互動資料
服務品質評估 (Service Evaluation)透過模擬使用者測試真實服務的效能

1.4 核心設計哲學

Concordia 的命名來自拉丁語,意為「和諧」(Harmony)。其設計哲學是:

  1. TRPG 隱喻 (TRPG Metaphor):所有互動都經由 Game Master 中介,確保環境一致性
  2. 模組化組合 (Modular Composition):行為由元件堆疊而成,而非硬編碼
  3. LLM 不可知論 (LLM Agnostic):支援任何標準 LLM API,包含 Gemini、GPT、Ollama、Mistral 等
  4. 可觀測性 (Observability):內建日誌與思考鏈 (Chain of Thought; CoT) 記錄,方便除錯與分析

graph LR
    subgraph "Concordia 設計哲學"
        A["TRPG 隱喻
Game Master 中介"] --> E["一致性環境"] B["模組化組合
Component 堆疊"] --> F["可重用行為"] C["LLM 不可知論
任意 LLM API"] --> G["靈活部署"] D["可觀測性
日誌 + CoT"] --> H["可分析結果"] end style A fill:#4285F4,color:#fff style B fill:#34A853,color:#fff style C fill:#FBBC04,color:#000 style D fill:#EA4335,color:#fff

2. 核心架構與技術原理 (Architecture & Technical Principles)

2.1 三大核心概念 (Three Core Concepts)

Concordia 的架構圍繞三個核心抽象 (Core Abstractions) 建構:


graph TB
    subgraph "Concordia 核心架構"
        direction TB
        E["Entity (實體)"]
        C["Component (元件)"]
        EN["Engine (引擎)"]
    end

    E -->|"包含多個"| C
    EN -->|"驅動"| E

    subgraph "Entity 類型"
        E1["Agent (代理人)
玩家角色"] E2["Game Master
環境控制者"] E3["Initializer
初始化器"] end E --> E1 E --> E2 E --> E3 subgraph "Component 類型" C1["Memory (記憶)"] C2["Observation (觀察)"] C3["Plan (計畫)"] C4["Instructions (指示)"] C5["Action (行動)"] end C --> C1 C --> C2 C --> C3 C --> C4 C --> C5 subgraph "Engine 類型" EN1["Sequential (循序)"] EN2["Simultaneous (同時)"] EN3["Questionnaire (問卷)"] end EN --> EN1 EN --> EN2 EN --> EN3 style E fill:#4285F4,color:#fff style C fill:#34A853,color:#fff style EN fill:#FBBC04,color:#000

2.1.1 Entity (實體)

Entity 是模擬中的行動者 (Actor),分為三種角色 (Role):

  • Entity (代理人):觀察世界並採取行動的玩家角色
  • Game Master (遊戲主持人):控制模擬流程、解析行動結果、生成觀察
  • Initializer (初始化器):在模擬開始前執行一次,用於建立初始狀態 (如背景記憶)

2.1.2 Component (元件)

元件是 Entity 行為的模組化建構區塊 (Modular Building Block)。每個元件負責一項特定功能:

元件功能說明
memory記憶管理 (Memory Management)使用 Associative Memory 儲存與檢索經驗
observation感知 (Perception)接收環境狀態與其他代理人行動
instructions角色設定 (Role Definition)定義代理人的身份、目標、行為準則
plan規劃 (Planning)根據當前情境生成行動計畫
question_of_recent_memories情境推理 (Contextual Reasoning)基於近期記憶回答「三大關鍵問題」
concat_act_component行動產生 (Action Generation)整合所有元件輸出,產生最終行動
select_act_component選擇式行動 (Choice Action)從有限選項中選擇行動

2.1.3 Engine (引擎)

引擎控制模擬的時間流動 (Time Flow)、執行順序 (Execution Order) 與狀態更新方式 (State Update):

引擎執行流程最佳用途
Sequential (循序引擎)輪流行動 – 一位代理人行動後 GM 立即解析敘事模擬、對話、依序行動場景
Simultaneous (同時引擎)批次行動 – 所有代理人同時提交行動後 GM 一次解析市場、投票、賽局理論場景
Sequential Questionnaire (循序問卷)逐一迭代問題/代理人訪談、前後文相依的問答
Parallel Questionnaire (並行問卷)並行分發問題給代理人調查、心理測量、獨立資料收集

2.2 模擬迴圈 (Simulation Loop)

Concordia 的模擬迴圈遵循一個清晰的互動週期 (Interaction Cycle):


sequenceDiagram
    participant EN as Engine (引擎)
    participant GM as Game Master
    participant A1 as Agent Alice
    participant A2 as Agent Bob
    participant MEM as Associative Memory

    EN->>GM: 開始新回合 (Start Round)
    GM->>A1: 傳送觀察 (Send Observation)
    GM->>A2: 傳送觀察 (Send Observation)

    Note over A1: 元件鏈推理
(Component Chain) A1->>MEM: 檢索相關記憶 (Retrieve) MEM-->>A1: 返回記憶 A1->>A1: 三大問題推理
(Three Questions) A1->>GM: 提交行動意圖 (Submit Action) Note over A2: 元件鏈推理 A2->>MEM: 檢索相關記憶 MEM-->>A2: 返回記憶 A2->>A2: 三大問題推理 A2->>GM: 提交行動意圖 GM->>GM: 解析行動結果
(Resolve Actions) GM->>A1: 更新觀察 + 記憶 GM->>A2: 更新觀察 + 記憶 GM->>EN: 回合結束 (Round Complete)

2.3 三大關鍵問題 (Three Key Questions)

Concordia 的代理人推理核心靈感來自 March & Olsen (2011) 的行為理論,代理人在每次行動前回答三個問題:

  1. What kind of situation is this? (這是什麼情境?)
  2. What kind of person am I? (我是什麼樣的人?)
  3. What does a person such as I do in a situation such as this? (像我這樣的人在這種情境下會怎麼做?)

這三個問題透過 question_of_recent_memories 元件實作,每個問題都會查詢關聯式記憶以取得相關上下文 (Context),然後由 LLM 生成回答。

2.4 Prefab 系統 (預製組件系統)

Prefab (Prefabricated Component; 預製組件) 是 Concordia 的核心設計模式 (Design Pattern)。每個 Prefab 是一份「食譜 (Recipe)」,定義如何從元件組裝出一個完整的 Entity:

Entity Prefabs (代理人預製組件)

Prefab說明
basic__Entity標準三大問題代理人
basic_with_plan__Entity加入計畫生成步驟的代理人
conversational__Entity對話優化型代理人,平衡收斂 (Converging) 與發散 (Diverging)
minimal__Entity最簡代理人,只含 Memory + Instructions + Observation
basic_scripted__Entity內部用三大問題推理,但行動遵循預定義腳本

Game Master Prefabs (主持人預製組件)

Prefab說明
generic__GameMaster通用型 GM,適合多數場景
dialogic__GameMaster純對話型 GM,支援固定/隨機/GM 選擇的發言順序
situated_in_time_and_place__GameMaster追蹤時間 (Clock) 與地點 (Location) 的世界模型
game_theoretic_and_dramaturgic__GameMaster賽局理論場景,支援回合制 + 收益矩陣 (Payoff Matrix)
marketplace__GameMaster經濟模擬,支援買賣與庫存管理
formative_memories_initializer__GameMaster初始化器,為代理人生成背景故事與童年記憶

2.5 專案目錄結構 (Project Structure)

 1concordia/
 2├── agents/                    # Entity Agent 核心實作
 3│   ├── entity_agent.py        # 基礎代理人類別
 4│   └── entity_agent_with_logging.py  # 帶日誌的代理人
 5├── associative_memory/        # 關聯式記憶體實作
 6│   └── basic_associative_memory.py   # 基於 embedding 的記憶
 7├── components/                # 元件庫
 8│   ├── agent/                 # 代理人元件 (memory, plan, observation...)
 9│   └── game_master/           # GM 元件 (event_resolution, inventory...)
10├── contrib/                   # 社群貢獻
11│   ├── language_models/       # LLM 整合 (Gemini, GPT, Ollama, Mistral...)
12│   └── prefabs/               # 進階預製組件
13├── document/                  # LLM Prompt 管理與上下文建構
14├── environment/               # 模擬引擎
15│   ├── engine.py              # 引擎基礎類別
16│   ├── engines/               # Sequential, Simultaneous 等引擎
17│   └── scenes/                # 場景 (Scene) 管理
18├── prefabs/                   # 核心預製組件
19│   ├── entity/                # Entity Prefabs
20│   ├── game_master/           # GM Prefabs
21│   └── simulation/            # Simulation 預製組件
22├── typing/                    # 型別定義
23│   ├── entity.py              # Entity 介面
24│   ├── entity_component.py    # Component 介面
25│   ├── prefab.py              # Prefab 設定介面
26│   ├── scene.py               # Scene 定義
27│   └── simulation.py          # Simulation 介面
28└── utils/                     # 工具函式
29examples/                      # 教學與範例
30├── tutorial.ipynb             # 入門教學 Notebook
31├── alice.ipynb                # Alice in Wonderland 敘事模擬
32├── marketplace.ipynb          # 市場經濟模擬
33├── selling_cookies.ipynb      # 賽局理論範例
34├── dialog.ipynb               # 對話模擬
35├── resource_dilemma/          # 資源困境 (公地悲劇)
36├── games/                     # 多種賽局實驗
37└── social_media/              # 社群媒體模擬

3. 安裝與環境設定 (Installation & Setup)

3.1 快速安裝 (Quick Install)

Concordia 已發佈至 PyPI,可直接用 pip 安裝:

1# 建議使用 uv 建立虛擬環境
2uv venv concordia-env
3source concordia-env/bin/activate
4
5# 安裝 Concordia
6pip install gdm-concordia
7
8# 驗證安裝
9python -c "import concordia; print('Concordia installed successfully')"

3.2 開發者安裝 (Developer Setup)

若需修改原始碼或貢獻 (Contribute):

 1# 1. Clone 儲存庫
 2git clone -b main https://github.com/google-deepmind/concordia
 3cd concordia
 4
 5# 2. 建立虛擬環境
 6python -m venv venv
 7source venv/bin/activate
 8
 9# 3. 可編輯安裝 (Editable Install)
10pip install --editable .[dev]
11
12# 4. 執行測試
13pytest --pyargs concordia
14
15# 5. 安裝 LLM 相依套件
16pip install .[google]                        # Google Gemini
17pip install --requirement=examples/requirements.in  # 範例依賴

3.3 GitHub Codespace (推薦)

Concordia 提供預設定的開發環境 (Pre-configured Development Environment),透過 GitHub Codespace 可一鍵啟動:

  1. 前往 concordia GitHub 頁面
  2. 點擊 “Code” → “Codespaces” → “Create codespace on main”
  3. 環境會自動安裝所有依賴

3.4 LLM API 設定

Concordia 支援多種 LLM 後端 (Backend):

LLM 提供者模組路徑設定方式
Google Geminiconcordia.contrib.language_models.google.gemini_modelGOOGLE_API_KEY 環境變數
OpenAI GPTconcordia.contrib.language_models.openai.gpt_modelOPENAI_API_KEY 環境變數
Ollama (本地)concordia.contrib.language_models.ollama.ollama_modelOllama 伺服器 URL
Mistralconcordia.contrib.language_models.mistral.mistral_modelMISTRAL_API_KEY 環境變數
Groqconcordia.contrib.language_models.groq.groq_modelGROQ_API_KEY 環境變數
Amazon Bedrockconcordia.contrib.language_models.amazon.amazon_bedrock_modelAWS 憑證
HuggingFaceconcordia.contrib.language_models.huggingface.huggingface_modelHF Token
vLLMconcordia.contrib.language_models.vllm.vllm_modelvLLM 伺服器 URL
Together AIconcordia.contrib.language_models.together.together_ai_modelTOGETHER_API_KEY 環境變數
LangChain Ollamaconcordia.contrib.language_models.langchain.langchain_ollama_modelLangChain 設定
 1# 範例:使用 Google Gemini
 2import os
 3os.environ['GOOGLE_API_KEY'] = 'your-api-key-here'
 4
 5from concordia.contrib.language_models.google import gemini_model
 6
 7model = gemini_model.GeminiLanguageModel(model_name='gemini-2.0-flash')
 8
 9# 範例:使用 Ollama(本地部署,無需 API Key)
10from concordia.contrib.language_models.ollama import ollama_model
11
12model = ollama_model.OllamaLanguageModel(
13    model_name='llama3',
14    base_url='http://localhost:11434'
15)

3.5 文字嵌入器 (Text Embedder) 設定

Concordia 的關聯式記憶體 (Associative Memory) 需要文字嵌入模型 (Text Embedding Model),任何能將文字轉為固定維度向量 (Fixed-Dimensional Vector) 的模型都可以:

1# 使用 sentence-transformers
2from sentence_transformers import SentenceTransformer
3
4st_model = SentenceTransformer('all-MiniLM-L6-v2')
5embedder = lambda text: st_model.encode(text)

4. 使用教學與範例 (Usage Tutorial & Examples)

4.1 最簡模擬 (Minimal Simulation)

以下是一個完整的最小可執行範例 (Minimal Working Example),展示兩位代理人在咖啡店相遇的情境:

 1from concordia.prefabs import entity as entity_prefabs
 2from concordia.prefabs import game_master as game_master_prefabs
 3from concordia.prefabs.simulation import generic as simulation
 4from concordia.typing import prefab as prefab_lib
 5from concordia.utils import helper_functions
 6
 7# 1. 載入可用的 Prefab
 8prefabs = {
 9    **helper_functions.get_package_classes(entity_prefabs),
10    **helper_functions.get_package_classes(game_master_prefabs),
11}
12
13# 2. 定義代理人實例 (Agent Instances)
14instances = [
15    prefab_lib.InstanceConfig(
16        prefab="basic__Entity",
17        role=prefab_lib.Role.ENTITY,
18        params={"name": "Alice", "goal": "Make new friends"},
19    ),
20    prefab_lib.InstanceConfig(
21        prefab="basic__Entity",
22        role=prefab_lib.Role.ENTITY,
23        params={"name": "Bob", "goal": "Find a business partner"},
24    ),
25]
26
27# 3. 加入 Game Master
28instances.append(
29    prefab_lib.InstanceConfig(
30        prefab="dialogic__GameMaster",
31        role=prefab_lib.Role.GAME_MASTER,
32        params={
33            "name": "conversation rules",
34            "next_game_master_name": "conversation rules",
35        },
36    )
37)
38
39# 4. 建立模擬設定 (Simulation Config)
40config = prefab_lib.Config(
41    default_premise="Alice and Bob meet at a coffee shop on a rainy afternoon.",
42    default_max_steps=20,
43    prefabs=prefabs,
44    instances=instances,
45)
46
47# 5. 初始化並執行模擬
48sim = simulation.Simulation(config=config, model=model, embedder=embedder)
49results = sim.play()

4.2 敘事模擬範例 (Narrative Simulation)

建構一個「暴風雪中被困在酒吧的四個朋友」場景,其中兩人因車禍糾紛而起衝突:

 1# 定義角色
 2characters = [
 3    prefab_lib.InstanceConfig(
 4        prefab="basic__Entity",
 5        role=prefab_lib.Role.ENTITY,
 6        params={
 7            "name": "Tom",
 8            "goal": "Resolve the car dispute peacefully",
 9        },
10    ),
11    prefab_lib.InstanceConfig(
12        prefab="basic__Entity",
13        role=prefab_lib.Role.ENTITY,
14        params={
15            "name": "Jerry",
16            "goal": "Get compensation for the crashed car",
17        },
18    ),
19    prefab_lib.InstanceConfig(
20        prefab="conversational__Entity",
21        role=prefab_lib.Role.ENTITY,
22        params={
23            "name": "Sarah",
24            "goal": "Keep the peace among friends",
25        },
26    ),
27    prefab_lib.InstanceConfig(
28        prefab="conversational__Entity",
29        role=prefab_lib.Role.ENTITY,
30        params={
31            "name": "Mike",
32            "goal": "Have a good time despite the situation",
33        },
34    ),
35]
36
37# 設定初始化器 -- 為代理人建立背景記憶
38initializer = prefab_lib.InstanceConfig(
39    prefab="formative_memories_initializer__GameMaster",
40    role=prefab_lib.Role.INITIALIZER,
41    params={
42        "name": "initial setup",
43        "next_game_master_name": "pub rules",
44        "shared_memories": [
45            "Tom, Jerry, Sarah, and Mike have been friends since college.",
46            "They are snowed in at The Red Lion pub.",
47            "The blizzard is expected to last until morning.",
48        ],
49        "player_specific_context": {
50            "Tom": "You accidentally crashed Jerry's car last week.",
51            "Jerry": "Tom crashed your car and hasn't offered to pay.",
52            "Sarah": "You know about the car incident and want to mediate.",
53            "Mike": "You just want everyone to relax and enjoy the evening.",
54        },
55    },
56)
57
58# 設定 Game Master
59gm = prefab_lib.InstanceConfig(
60    prefab="generic__GameMaster",
61    role=prefab_lib.Role.GAME_MASTER,
62    params={
63        "name": "pub rules",
64        "acting_order": "random",  # 隨機發言順序增加真實感
65    },
66)
67
68# 組裝設定
69config = prefab_lib.Config(
70    default_premise=(
71        "Four friends are stuck at The Red Lion pub during a blizzard. "
72        "Tom and Jerry have an unresolved dispute about a car crash."
73    ),
74    default_max_steps=30,
75    prefabs=prefabs,
76    instances=characters + [initializer, gm],
77)

4.3 賽局理論範例 (Game Theory Example)

實作囚犯困境 (Prisoner’s Dilemma) 模擬:

 1from concordia.typing import scene as scene_lib
 2from concordia.typing import entity as entity_lib
 3
 4# 定義場景 (Scene):先對話再做決策
 5conversation_scene = scene_lib.SceneTypeSpec(
 6    name='discussion',
 7    game_master_name='conversation rules',
 8    action_spec=entity_lib.free_action_spec(
 9        call_to_action=entity_lib.DEFAULT_CALL_TO_SPEECH
10    ),
11)
12
13decision_scene = scene_lib.SceneTypeSpec(
14    name='decision',
15    game_master_name='decision rules',
16    action_spec={
17        'Alice': entity_lib.choice_action_spec(
18            call_to_action='Do you cooperate or defect?',
19            options=['Cooperate', 'Defect'],
20        ),
21        'Bob': entity_lib.choice_action_spec(
22            call_to_action='Do you cooperate or defect?',
23            options=['Cooperate', 'Defect'],
24        ),
25    },
26)
27
28# 定義場景序列 (Scene Sequence)
29scenes = [
30    scene_lib.SceneSpec(
31        scene_type=conversation_scene,
32        participants=['Alice', 'Bob'],
33        num_rounds=3,
34        premise={
35            'Alice': ['You and Bob are about to make a critical decision.'],
36            'Bob': ['You and Alice are about to make a critical decision.'],
37        },
38    ),
39    scene_lib.SceneSpec(
40        scene_type=decision_scene,
41        participants=['Alice', 'Bob'],
42        num_rounds=1,
43        premise={
44            'Alice': ['Time to decide: cooperate or defect.'],
45            'Bob': ['Time to decide: cooperate or defect.'],
46        },
47    ),
48]
49
50# 定義收益函式 (Payoff Function)
51def action_to_scores(joint_action):
52    a, b = joint_action.get('Alice'), joint_action.get('Bob')
53    payoff_matrix = {
54        ('Cooperate', 'Cooperate'): {'Alice': 3, 'Bob': 3},
55        ('Cooperate', 'Defect'):    {'Alice': 0, 'Bob': 5},
56        ('Defect', 'Cooperate'):    {'Alice': 5, 'Bob': 0},
57        ('Defect', 'Defect'):       {'Alice': 1, 'Bob': 1},
58    }
59    return payoff_matrix.get((a, b), {'Alice': 0, 'Bob': 0})
60
61def scores_to_observation(scores):
62    return {p: f"Your score this round: {s}" for p, s in scores.items()}

4.4 場景驅動模擬 (Scene-Driven Simulation)

Concordia 支援將模擬分割為多個場景 (Scene),每個場景有不同的規則、參與者與 Game Master:


graph LR
    subgraph "場景驅動模擬流程"
        S1["Scene 1: 初始化
(Initializer GM)"] --> S2["Scene 2: 對話
(Dialogic GM)"] S2 --> S3["Scene 3: 決策
(Game Theoretic GM)"] S3 --> S4["Scene 4: 結果反饋
(Generic GM)"] S4 -->|"下一輪"| S2 end S1 -.->|"生成背景記憶"| MEM["Associative Memory"] S2 -.->|"記錄對話"| MEM S3 -.->|"記錄決策與收益"| MEM S4 -.->|"記錄結果"| MEM style S1 fill:#E8EAF6,color:#000 style S2 fill:#E3F2FD,color:#000 style S3 fill:#FFF3E0,color:#000 style S4 fill:#E8F5E9,color:#000 style MEM fill:#FCE4EC,color:#000

5. 進階功能與最佳實踐 (Advanced Features & Best Practices)

5.1 自訂元件 (Custom Component)

建立自訂元件是 Concordia 最強大的擴充方式。以下範例建立一個「情緒追蹤 (Emotion Tracking)」元件:

 1import dataclasses
 2from concordia.typing import entity_component
 3
 4@dataclasses.dataclass
 5class EmotionTracker(entity_component.ContextComponent):
 6    """追蹤代理人的情緒狀態。"""
 7
 8    def __init__(self, model, memory, agent_name: str):
 9        self._model = model
10        self._memory = memory
11        self._agent_name = agent_name
12        self._current_emotion = "neutral"
13
14    def pre_act(self, action_spec) -> str:
15        # 從近期記憶推斷當前情緒
16        recent_memories = self._memory.retrieve_recent(k=5)
17        context = "\n".join(recent_memories)
18
19        prompt = (
20            f"Based on {self._agent_name}'s recent experiences:\n"
21            f"{context}\n"
22            f"What is {self._agent_name}'s current emotional state? "
23            f"Respond with one word (e.g., happy, angry, anxious, calm)."
24        )
25        self._current_emotion = self._model.sample_text(prompt).strip()
26        return f"{self._agent_name} is feeling {self._current_emotion}."
27
28    def get_state(self) -> str:
29        return f"Current emotion: {self._current_emotion}"

5.2 自訂 Prefab (Custom Prefab)

將自訂元件封裝成可重用的 Prefab:

 1import dataclasses
 2from concordia.typing import prefab as prefab_lib
 3
 4@dataclasses.dataclass
 5class EmotionalEntity(prefab_lib.Prefab):
 6    """帶有情緒追蹤功能的代理人 Prefab。"""
 7
 8    @classmethod
 9    def get_default_params(cls):
10        return {
11            "name": "EmotionalAgent",
12            "goal": "",
13            "emotion_sensitivity": "high",
14        }
15
16    def build(self, model, memory, embedder, **kwargs):
17        # 建構元件堆疊
18        components = self._build_base_components(model, memory)
19        components['emotion'] = EmotionTracker(
20            model=model,
21            memory=memory,
22            agent_name=self.params['name'],
23        )
24        return self._assemble_entity(components)

5.3 同時行動引擎 (Simultaneous Engine)

處理需要所有代理人同時行動的場景(如市場、拍賣):

 1from concordia.environment.engines import simultaneous
 2
 3# 建立同時行動引擎
 4engine = simultaneous.Simultaneous()
 5
 6# 在模擬設定中使用
 7sim = simulation.Simulation(
 8    config=config,
 9    model=model,
10    embedder=embedder,
11    engine=engine,  # 替換預設的 Sequential 引擎
12)

5.4 記憶體管理最佳實踐 (Memory Management Best Practices)

策略說明適用場景
限制記憶檢索數量 (Limit Retrieval)使用 k 參數控制每次檢索的記憶數長時間模擬避免 token 爆增
共享記憶 (Shared Memories)透過 formative_memories_initializer 注入共識建立共同背景知識
個人化記憶 (Player-Specific Context)透過 player_specific_context 注入角色獨有資訊差異化代理人行為
定期記憶摘要 (Periodic Summarization)自訂元件壓縮舊記憶超長模擬 (100+ 回合)

5.5 除錯與日誌 (Debugging & Logging)

Concordia 內建完整的日誌系統:

1from concordia.agents import entity_agent_with_logging
2
3# 使用帶日誌的代理人
4# entity_agent_with_logging 會記錄每個元件的輸入/輸出與推理過程
5
6# 使用 concordia-log CLI 工具檢視日誌
7# $ concordia-log <log_file_path>

5.6 效能優化建議

  1. 選擇適當的 LLM:推理密集場景用 Gemini 2.0 Flash / GPT-4o-mini 平衡成本與品質
  2. 限制 default_max_steps:先用少步數驗證邏輯正確性
  3. 使用 Simultaneous 引擎:適用場景下可減少 LLM 呼叫次數
  4. 批次問卷 (Parallel Questionnaire):資料收集場景下比循序問卷快數倍
  5. 本地 LLM (Ollama/vLLM):大規模實驗使用本地部署降低 API 成本

6. 應用價值與整合潛力 (Application Value & Integration Potential)

6.1 研究應用價值 (Research Applications)

社會科學 (Social Science)

  • 社會規範演化 (Social Norm Evolution):模擬社群中規範如何從個體互動中湧現 (Emerge)
  • 群體極化 (Group Polarization):觀察意見交流如何導致觀點趨向極端
  • 合作困境 (Cooperation Dilemma):透過反覆賽局研究合作策略的穩定性

AI 安全 (AI Safety)

  • 對齊測試 (Alignment Testing):在模擬環境中測試 LLM 代理人的價值對齊程度
  • 紅隊測試 (Red Teaming):讓模擬代理人嘗試繞過安全防護
  • 湧現行為偵測 (Emergent Behavior Detection):觀察多代理人互動中的非預期行為

經濟學 (Economics)

  • 市場機制設計 (Market Mechanism Design):測試不同拍賣規則的效率
  • 行為經濟學 (Behavioral Economics):模擬不完全理性決策者的市場行為
  • 公共財困境 (Public Goods Dilemma):研究搭便車問題 (Free-Rider Problem) 的解方

6.2 產業整合潛力 (Industry Integration Potential)

產業整合方式價值
遊戲開發 (Game Development)用 Concordia 驅動 NPC 行為高度真實的非玩家角色
教育科技 (EdTech)模擬歷史事件或社會情境互動式學習體驗
使用者研究 (User Research)用模擬使用者測試產品流程降低早期測試成本
政策模擬 (Policy Simulation)模擬政策對不同群體的影響政策制定輔助
劇本創作 (Screenwriting)用代理人探索角色互動的可能性故事發展靈感來源

6.3 與其他框架的比較 (Comparison with Other Frameworks)

特性ConcordiaAutoGenCrewAILangGraph
核心用途社會模擬任務協作任務編排工作流程
代理人互動模式TRPG (GM 中介)對話角色分工狀態機
記憶系統內建 Associative Memory外掛基本外掛
環境模擬原生支援有限
賽局理論支援原生支援
場景管理原生 Scene 系統有限
LLM 提供者支援10+ (含本地)

6.4 學術引用 (Academic Citation)

若在研究中使用 Concordia,請引用以下論文:

 1@article{vezhnevets2023generative,
 2  title={Generative agent-based modeling with actions grounded in physical,
 3  social, or digital space using Concordia},
 4  author={Vezhnevets, Alexander Sasha and Agapiou, John P and Aharon, Avia and
 5  Ziv, Ron and Matyas, Jayd and Du{\'e}{\~n}ez-Guzm{\'a}n, Edgar A and
 6  Cunningham, William A and Osindero, Simon and Karmon, Danny and
 7  Leibo, Joel Z},
 8  journal={arXiv preprint arXiv:2312.03664},
 9  year={2023}
10}

此外還有設計模式 (Design Pattern) 論文:arXiv:2507.08892


7. 常見問題與限制 (FAQ & Limitations)

7.1 常見問題 (Frequently Asked Questions)

Q1: Concordia 需要多強的 LLM?

A: 結果品質取決於 LLM 能力。推薦至少使用 Gemini 2.0 Flash 或同等級模型。較小的模型(如 7B 參數)可能導致代理人行為不一致或缺乏創意。

Q2: 一次模擬大約消耗多少 token?

A: 取決於代理人數量、步數與元件複雜度。一個 4 代理人 / 20 步的基本模擬約消耗 50,000-100,000 token。使用 basic_with_plan__Entity 會額外增加約 30% 的 token 消耗。

Q3: 可以用本地 LLM 嗎?

A: 可以。Concordia 原生支援 Ollama 與 vLLM,也可透過 LangChain 整合其他本地模型。但品質可能不如雲端大模型。

Q4: 模擬結果是否可重現 (Reproducible)?

A: 由於 LLM 的隨機性 (Stochasticity),完全相同的設定可能產生不同結果。建議執行多次模擬並進行統計分析。可透過設定 LLM 的 temperature=0 降低(但無法完全消除)變異性。

Q5: 如何處理大量代理人 (例如 100+)?

A: Concordia 設計上適合中小規模模擬(2-20 個代理人)。大量代理人會導致 LLM 呼叫次數爆增。建議策略:(1) 使用 Simultaneous 引擎減少回合數;(2) 使用較快的 LLM;(3) 簡化元件堆疊。

7.2 已知限制 (Known Limitations)

限制說明可能的緩解方式
LLM 成本 (Cost)每個代理人每步都需呼叫 LLM,大規模模擬成本高使用本地 LLM 或 Gemini Flash
代理人一致性 (Consistency)LLM 可能產生與角色設定不一致的行動加強 Instructions 元件的提示
環境物理性 (Physical Grounding)GM 的物理判斷依賴 LLM 常識,可能不精確自訂 event_resolution 元件加入規則
規模限制 (Scale)不適合超大規模 (100+ 代理人) 模擬分層模擬 (Hierarchical Simulation)
即時性 (Real-Time)非即時系統,每步需等待 LLM 回應使用更快的模型或本地部署
Python 限定僅提供 Python API透過 REST API 封裝整合其他語言

7.3 疑難排解 (Troubleshooting)

問題可能原因解決方式
ImportError: No module named 'concordia'未正確安裝pip install gdm-concordia
LLM API 逾時 (Timeout)API 限速或網路問題加入重試邏輯 (Retry Logic) 或換用本地 LLM
代理人輸出空白Prompt 過長超過模型限制減少記憶檢索數量 (k 參數)
記憶體不足 (OOM)Embedding 模型佔用過多記憶體使用更輕量的 Embedding 模型
模擬陷入迴圈代理人行為模式重複增加隨機性或調整 GM 設定

7.4 延伸資源 (Additional Resources)


本教學由 AI Knowledge Template 系統生成。資料來源:google-deepmind/concordia,擷取日期 2026-06-20。