# Conversation

The `Conversation` class orchestrates structured message exchange between agents and users in Web3 workflows. Designed for audit compliance and post-execution analysis, it tracks dialog history across DeFi operations, multi-chain negotiations, and governance voting systems. Supports ZK-proofs for tamper-evident conversation logging.

***

#### **Key Features**

1. **Role-Based Messaging**: Track `user`, `agent`, `smart_contract`, and `oracle` roles.
2. **On-Chain Anchoring**: Auto-save critical messages to IPFS with Filecoin backups.
3. **Cross-Agent Search**: Full-text search across 10M+ message histories.
4. **Compliance Mode**: Redact sensitive data (e.g., wallet addresses) in exports.

***

#### **Class Definition**

**Message Schema (`BaseModel`)**

```python
from pydantic import BaseModel  
from datetime import datetime  

class Message(BaseModel):  
    role: str                   # "user", "agent", "contract", "oracle"  
    content: str                # Raw message content  
    timestamp: datetime         # UTC timestamp  
    tx_hash: Optional[str]      # Associated blockchain transaction  
    zk_proof: Optional[str]      # Proof of message ordering integrity  
```

**Conversation**

```python
class Conversation:  
    def __init__(  
        self,  
        compliance_mode: bool = False,  # GDPR/OFAC redaction  
        enable_zk: bool = True          # Generate ZK proofs  
    ):  
        self.messages: List[Message] = []  
        self.compliance = compliance_mode  
        self.zk_enabled = enable_zk  
```

***

#### **Core Methods**

**1. Add Message**

```python
def add(  
    self,  
    role: Literal["user", "agent", "contract"],  
    content: str,  
    tx_hash: Optional[str] = None  
) -> str:  
    """  
    :param role: Sender type  
    :param content: Message text/transaction data  
    :param tx_hash: Related on-chain TX hash (if applicable)  
    :return: CID of IPFS-stored message (if ZK enabled)  
    """  
    message = Message(role=role, content=content, tx_hash=tx_hash)  
    if self.zk_enabled:  
        message.zk_proof = generate_zk_proof(self.messages[-1] if self.messages else None)  
    self.messages.append(message)  
    return message.zk_proof or ""  
```

**2. Search Messages**

```python
def search(  
    self,  
    query: str,  
    filters: Optional[Dict] = None  # {role: "contract", date_range: ("2025-02-01", "2025-02-06")}  
) -> List[Message]:  
    """Semantic search with LLM-based query understanding"""  
    return search_engine(query, self.messages, filters)  
```

***

#### **Enterprise Use Cases**

**1. DAO Governance Logging**

```python
conv = Conversation(compliance_mode=True)  
conv.add("user", "Proposal #325: Increase treasury ETH allocation to 40%")  
conv.add("contract", "VotingContract: 0x23f4...c7da initiated", tx_hash="0x1298...d8f3")  
conv.export("dao_vote_325.json")  # ZK-anchored to IPFS  
```

**2. Cross-Chain Negotiation**

```python
conv = Conversation(enable_zk=True)  
conv.add("agent", "Offer: 100 ETH swap for 1.2m USDC on Uniswap")  
conv.add("oracle", "Chainlink ETH/USD: 3284.55")  
conv.add("contract", "Swap executed: 0x98a1...b2c1")  
```

***

#### **Performance Metrics**

| **Operation**         | 1K Messages | 1M Messages |
| --------------------- | ----------- | ----------- |
| Add Message           | 0.4ms       | 0.5ms       |
| Search (Keyword)      | 8ms         | 1.2s        |
| Search (Semantic)     | 120ms       | 18s         |
| Export with ZK-Proofs | 320ms       | 42s         |

***

#### **Best Practices**

**1. Compliance Handling**

```python
# Auto-redact wallet addresses in exports  
conv = Conversation(compliance_mode=True)  
conv.export("log.json")  # Replaces 0x123... with [REDACTED]  
```

**2. Cross-Agent Integration**

```python
class ComplianceAgent:  
    def __init__(self):  
        self.conv = Conversation()  

    def approve_tx(self, tx_data):  
        self.conv.add("agent", f"Approved TX: {tx_data['amount']} ETH")  
        return self.conv.messages[-1].zk_proof  
```

***

#### **Usage Examples**

**1. Basic Message Logging**

```python
from agentgpt.structs import Conversation  

conv = Conversation()  
conv.add("user", "Swap 1 ETH to USDC")  
conv.add("contract", "UniswapV3 swap executed: 0x98a1...b2c1")  
print(conv.search("USDC"))  
```

**2. Cross-Chain Audit Trail**

```python
conv = Conversation(enable_zk=True)  

# Step 1: User request  
conv.add("user", "Bridge 10 ETH to Polygon", tx_hash="0x12a8...d9f4")  

# Step 2: Bridge contract interaction  
conv.add("contract", "Locked 10 ETH: 0x23b1...e5c6")  

# Step 3: Polygon settlement  
conv.add("contract", "Minted 10 WETH: 0x89c2...f7a1")  

# Export with ZK proofs  
conv.export("bridge_audit.zip")  
```


---

# 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/structs/conversation.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.
