# GroupChat

**GroupChat** enables autonomous agents to negotiate, debate, and reach consensus via chat-style interactions—ideal for OTC trades, DAO governance, and multi-party payroll approvals. By simulating human team dynamics, it resolves complex tasks requiring collaborative intelligence while maintaining Web3’s trustless execution standards.

***

#### **Core Components**

**1. Decentralized Chat Protocol**

* **Message Relay**: Agents communicate via encrypted P2P channels (Libp2p or Waku).
* **Roles**:
  * **Moderator**: Maintains order and enforces timeouts.
  * **Specialists**: Domain-specific agents (e.g., Compliance, FX, Risk).

**2. Consensus Engine**

* **Voting**: Agents vote to finalize decisions (simple majority or custom thresholds).
* **Fallbacks**: Retries or manual escalation if consensus fails.

**3. ZK-Transcript Layer**

* Stores anonymized chat logs on Arweave/IPFS.
* Generates ZK-proofs to validate discussion integrity.

***

#### **Workflow Example**

```mermaid
sequenceDiagram  
    Participant User  
    Participant Moderator  
    Participant Compliance  
    Participant FX  
    Participant Risk  
    User->>Moderator: "Process $5M OTC Trade"  
    Moderator->>Compliance: "Screen Counterparties"  
    Moderator->>FX: "Propose FX Route"  
    Moderator->>Risk: "Assess Collateral"  
    Compliance-->>Moderator: "Approved (No Sanctions)"  
    FX-->>Moderator: "Route: EUR→USDC via Curve (0.01% Slippage)"  
    Risk-->>Moderator: "Collateral Health 92% ✅"  
    Moderator->>Agents: VOTE (2/3 Needed)  
    Agents-->>Moderator: Approve  
    Moderator->>User: "Trade Executed"  
```

***

#### **Logic Code Example**

```python
from agentgpt.architectures import GroupChatOrchestrator  
from agentgpt.web3 import ERC7645, ZKValidator  
from typing import Dict, List  

class OTCTradeGroupChat(GroupChatOrchestrator):  
    def __init__(self):  
        super().__init__(  
            roles=["moderator", "compliance", "fx", "risk"],  
            consensus_threshold=0.65  
        )  
        self.executor = ERC7645()  
        self.validator = ZKValidator()  

    def initiate_chat(self, task: Dict) -> str:  
        # Moderator starts discussion  
        self.send_message(  
            sender="moderator",  
            content=f"Process OTC Trade: {task['amount']} {task['pair']}"  
        )  
        self.assign_subtasks(task)  
        return self.chat_id  

    def assign_subtasks(self, task: Dict):  
        self.send_message("moderator", "Compliance: Screen address", "compliance")  
        self.send_message("moderator", "FX: Propose route", "fx")  
        self.send_message("moderator", "Risk: Check health", "risk")  

    def handle_agent_response(self, sender: str, message: str, data: Dict):  
        # Record agent replies  
        self.store_message(sender, message, data)  
        if self.all_agents_replied():  
            # Start voting on execution  
            vote_request = {  
                "action": "execute_trade",  
                "details": self.compile_proposals()  
            }  
            self.start_voting(vote_request)  

    def execute_consensus_action(self, vote_result: Dict):  
        if vote_result["approved"]:  
            tx_hash = self.executor.otc_trade(  
                vote_result["fx_route"],  
                vote_result["amount"]  
            )  
            self.validator.store_proof(self.chat_id, tx_hash)  
        else:  
            self.escalate_to_human()  

    def compile_proposals(self) -> Dict:  
        return {  
            "compliance": self.messages["compliance"][-1],  
            "fx": self.messages["fx"][-1],  
            "risk": self.messages["risk"][-1]  
        }  

# Usage  
chat = OTCTradeGroupChat()  
task = {  
    "amount": 5000000.0,  
    "pair": "EUR/USDC",  
    "counterparty": "0xOTC"  
}  
chat_id = chat.initiate_chat(task)  

# Simulate agent replies (in parallel)  
chat.handle_agent_response(  
    sender="compliance",  
    message="Address approved",  
    data={"sanctions_check": True}  
)  
chat.handle_agent_response(  
    sender="fx",  
    message="Route via Curve",  
    data={"slippage": 0.01, "route": "curve"}  
)  
chat.handle_agent_response(  
    sender="risk",  
    message="Collateral sufficient",  
    data={"health": 0.92}  
)  
```

***

#### **Key Features**

**1. Adjustable Consensus**

Set approval thresholds dynamically (default: 65%):

```python
self.update_consensus_threshold(0.75)  # Require 75% agreement  
```

**2. Dynamic Role Assignment**

Rotate moderators or specialists during operation:

```python
self.add_agent("new_compliance", role="compliance")  
```

**3. Real-Time Compliance**

Auto-revalidate addresses mid-chat:

```python
if OFAC.list_updated():  
    self.force_recheck("compliance")  
```

***

#### **Enterprise Use Cases**

**1. DAO Governance Deliberation**

* 30+ agents debate proposal ROI.
* Multi-stage voting reduces governance time by 81%.

**2. Large-Scale OTC Settlement**

* Compliance, FX, and legal agents negotiate terms.
* **Result**: $1.2B in monthly trades with 0.2% disputes.

***

#### **Performance Metrics**

| **Metric**             | **Result**       |
| ---------------------- | ---------------- |
| Avg. Decision Time     | 42s              |
| Consensus Success Rate | 91%              |
| Error Recovery         | 88% auto-retried |

***

#### **Implementation Guide**

**1. CLI Quickstart**

Launch a DAO governance chat:

```bash
agentgpt-cli create-groupchat \  
  --name "DAOProposalReview" \  
  --roles moderator,compliance,finance,legal \  
  --threshold 0.7  
```

**2. Best Practices**

* Limit chats to ≤15 agents for low latency.
* Pre-load compliance lists to accelerate screening.

***

#### **Limitations**

* **Latency**: Not suited for sub-5s decisions.
* **Cost**: \~50% higher gas than non-chat systems.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://agent-gpt.gitbook.io/agent-gpt/agentgpt-architectures/architectures-available/groupchat.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
