# Multi-Agent

**Use Case Overview**

**Scenario**: Financial Transaction Fraud Detection System\
**Agents**:

1. **TransactionAnalyzer**: NLP agent inspecting transaction descriptions.
2. **RiskScorer**: Statistical model calculating fraud probability (0-100).
3. **ComplianceLogger**: Audit-focused agent generating regulatory reports.

***

#### **Prerequisites**

* AgentGPT SDK ≥2.3 (supports agent-to-agent messaging).
* Basic understanding of **Choreography vs Orchestration**.

***

#### **1. Designing Agent Roles**

**Agent 1: Transaction Analyzer**

```python
from agentgpt import Agent, ToolSet

class TransactionAnalyzer(Agent):
    def __init__(self):
        super().__init__(name="TX-Analyzer-v1", role="Detect suspicious patterns")
        self.nlp_engine = ToolSet.load("gpt4-fincrime")  # Pre-trained financial crime model
        
    async def analyze(self, transaction: dict) -> dict:
        risk_flags = await self.nlp_engine.detect_anomalies(
            text=transaction["description"],
            metadata=transaction["metadata"]
        )
        return {"risk_flags": risk_flags, "tx_id": transaction["id"]}
```

**Agent 2: Risk Scorer**

```python
class RiskScorer(Agent):
    def __init__(self):
        super().__init__(name="Risk-Model-v3", role="Calculate fraud probability")
        self.model = ToolSet.load("xgb-risk-v2")  # XGBoost model trained on historical data
        
    async def evaluate(self, data: dict) -> float:
        return await self.model.predict(
            features=[data["amount"], data["risk_flags"], data["user_behavior_score"]]
        )
```

***

#### **2. Creating the Workflow**

**Sequential Workflow with Fallbacks**

```python
from agentgpt.workflows import OrchestratedWorkflow
from tenacity import retry, stop_after_attempt

class FraudDetectionFlow(OrchestratedWorkflow):
    def __init__(self):
        super().__init__(name="Fraud-Detection-v2")
        self.analyzer = TransactionAnalyzer()
        self.scorer = RiskScorer()
        self.logger = ComplianceLogger()
        
    @retry(stop=stop_after_attempt(3)) 
    async def execute(self, transaction: dict) -> dict:
        # Phase 1: Text analysis
        analysis = await self.analyzer.analyze(transaction)
        
        # Phase 2: Risk scoring
        risk_score = await self.scorer.evaluate({
            **transaction,
            "risk_flags": analysis["risk_flags"]
        })
        
        # Phase 3: Log for compliance
        await self.logger.audit({
            "tx_id": transaction["id"],
            "risk_score": risk_score,
            "decision": "block" if risk_score > 85 else "allow"
        })
        
        return {"tx_id": transaction["id"], "risk_score": risk_score}
```

***

#### **3. Deployment & Scaling**

**Kubernetes Configuration**

```yaml
# fraud-detection-deploy.yaml
agents:
  - name: tx-analyzer
    image: agentgpt/analyzer:2.1
    replicas: 5
    resources:
      limits:
        cpu: "2"
        memory: "4Gi"
        
  - name: risk-scorer
    image: agentgpt/risk-model:1.8
    replicas: 3
    gpu: 1  # Utilizes NVIDIA A10G for model inference
```

Deploy with:

```bash
agentgpt cluster apply -f fraud-detection-deploy.yaml
```

***

#### **4. Simulating Workflow Execution**

**Trigger via CLI**

```bash
agentgpt workflow trigger fraud-detection-v2 \
  --input '{
    "id": "TX-2025-3317",
    "amount": 12450.00,
    "description": "Cryptocurrency purchase → wallet address 0x3F5...1A",
    "user_behavior_score": 62
  }'
```

**Output**

```json
{
  "tx_id": "TX-2025-3317",
  "risk_score": 92.4,
  "audit_trail": "/audits/TX-2025-3317.log",
  "acted_on_by": ["TX-Analyzer-v1", "Risk-Model-v3"]
}
```

***

#### **5. Monitoring Inter-Agent Dependencies**

**Cluster Status Check**

```bash
agentgpt cluster status --workflow fraud-detection-v2
```

**Output**:

```
AGENT NAME         TASKS PROCESSED  ERROR RATE  AVG LATENCY  
tx-analyzer        12,314           0.12%       217ms  
risk-scorer        9,887            0.08%       184ms  
compliance-logger  12,314           0.04%       92ms  
```

***

#### **6. Best Practices for Multi-Agent Systems**

1. **Idempotency**: Ensure agents handle duplicate messages safely.
2. **Circuit Breakers**: Use `AgentGPT.circuit_breaker(max_failures=5)` for dependency failures.
3. **Parallelism**: Split workloads via `AgentSwarm` for high-throughput tasks.
4. **Version Control**: Tag agent versions to prevent compatibility issues.

***

#### **7. Troubleshooting**

| **Issue**             | **Debug Command**                            |
| --------------------- | -------------------------------------------- |
| Agent A → B timeout   | `agentgpt logs --follow --agent A,B`         |
| Workflow stuck        | `agentgpt workflow retry --id <WORKFLOW_ID>` |
| High GPU memory usage | `agentgpt metrics gpu --agent risk-scorer`   |


---

# 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/examples/multi-agent.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.
