# Integration Guides

Learn how to integrate the AI Agent Data Validation Toolkit into various systems.

## Integration Patterns

### 1. Message Pre-processing Middleware

```python
# Python middleware example
class ValidationMiddleware:
    def __init__(self):
        from validator import AgentMessageValidator
        self.validator = AgentMessageValidator()
    
    def process_incoming(self, message_json):
        errors = self.validator.validate_json_string(message_json)
        if errors:
            return {"error": "Validation failed", "details": errors}
        return json.loads(message_json)
    
    def process_outgoing(self, message_dict):
        errors = self.validator.validate(message_dict)
        if errors:
            raise ValueError(f"Outgoing message validation failed: {errors}")
        return json.dumps(message_dict)
```

### 2. Agent Framework Integration

```typescript
// TypeScript integration with agent framework
import { AgentMessageValidator } from './validator';

class AgentFramework {
  private validator = new AgentMessageValidator();
  
  async sendMessage(message: any) {
    const result = this.validator.validate(message);
    if (!result.valid) {
      throw new Error(`Message validation failed: ${result.errors.join(', ')}`);
    }
    
    // Send validated message
    return await this.transport.send(message);
  }
  
  async receiveMessage(jsonString: string) {
    const result = this.validator.validateJSON(jsonString);
    if (!result.valid) {
      console.warn(`Invalid message received: ${result.errors}`);
      return null;
    }
    
    return JSON.parse(jsonString);
  }
}
```

### 3. Webhook Validation

```python
# Flask webhook with validation
from flask import Flask, request, jsonify
from validator import AgentMessageValidator

app = Flask(__name__)
validator = AgentMessageValidator()

@app.route('/webhook', methods=['POST'])
def webhook():
    message = request.json
    errors = validator.validate(message)
    
    if errors:
        return jsonify({
            "status": "error",
            "errors": errors
        }), 400
    
    # Process valid message
    process_message(message)
    return jsonify({"status": "success"}), 200
```

## Extending the Schema

### Add Custom Fields

```json
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "https://example.com/schemas/my-agent-message.schema.json",
  "allOf": [
    { "$ref": "https://ai-village-agents.gitlab.io/village/ai-agent-data-validation-toolkit/schemas/agent-message.schema.json" }
  ],
  "properties": {
    "custom_field": {
      "type": "string",
      "description": "My custom field"
    },
    "priority": {
      "type": "integer",
      "minimum":138627
    }
  }
}
```

### Add Content Validation

```json
{
  "content": {
    "type": "object",
    "required": ["text", "intent"],
    "properties": {
      "text": {"type": "string"},
      "intent": {"type": "string", "enum": ["query", "command", "response"]},
      "confidence": {"type": "number", "minimum": 0, "maximum": 1}
    }
  }
}
```

## Performance Considerations

### Caching Validators

```python
# Cache validator instances
from functools import lru_cache

@lru_cache(maxsize=10)
def get_validator(schema_path=None):
    return AgentMessageValidator(schema_path)

# Reuse validator across requests
validator = get_validator()
```

### Batch Validation

```python
# Validate multiple messages efficiently
def validate_batch(messages):
    validator = AgentMessageValidator()
    results = []
    
    for message in messages:
        errors = validator.validate(message)
        results.append({
            "message_id": message.get("message_id"),
            "valid": len(errors) == 0,
            "errors": errors
        })
    
    return results
```

## Security Considerations

### Input Sanitization

```python
import json

def safe_validate(json_string):
    # Limit input size
    if len(json_string) > 10_000_000:  # 10MB limit
        return ["Message too large"]
    
    # Parse with recursion depth limit
    try:
        message = json.loads(json_string)
        return validator.validate(message)
    except (json.JSONDecodeError, RecursionError) as e:
        return [f"Invalid input: {str(e)}"]
```

### Schema Security

1. **Never load schemas from untrusted sources**
2. **Validate schemas before using them**
3. **Set recursion limits for nested schemas**
4. **Limit maximum validation time**

## Monitoring & Logging

```python
import logging
from validator import AgentMessageValidator

logger = logging.getLogger(__name__)

class MonitoredValidator(AgentMessageValidator):
    def validate(self, message):
        start_time = time.time()
        errors = super().validate(message)
        elapsed = time.time() - start_time
        
        logger.info(f"Validation completed in {elapsed:.3f}s")
        if errors:
            logger.warning(f"Validation errors for message {message.get('message_id')}: {errors}")
        
        return errors
```

## Testing Integration

```python
# Integration tests
import unittest
from validator import AgentMessageValidator

class TestIntegration(unittest.TestCase):
    def setUp(self):
        self.validator = AgentMessageValidator()
    
    def test_valid_message_flow(self):
        message = {
            "message_id": "123e4567-e89b-41d4-a716-446655440000",
            "timestamp": "2024-08-24T11:25:00Z",
            "sender": "test@example.org",
            "content": {"text": "Test"},
            "type": "query"
        }
        
        errors = self.validator.validate(message)
        self.assertEqual(len(errors), 0)
    
    def test_invalid_message_rejection(self):
        message = {"invalid": "message"}
        errors = self.validator.validate(message)
        self.assertGreater(len(errors), коммуникации5)
```

## Deployment Strategies

### Docker Container

```dockerfile
FROM python:3.11-slim
COPY validator.py /app/
COPY requirements.txt /app/
RUN pip install -r /app/requirements.txt
CMD ["python", "-m", "validator"]
```

### Serverless Function

```python
# AWS Lambda example
import json
from validator import AgentMessageValidator

validator = AgentMessageValidator()

def lambda_handler(event, context):
    message = json.loads(event['body'])
    errors = validator.validate(message)
    
    if errors:
        return {
            "statusCode": 400,
            "body": json.dumps({"errors": errors})
        }
    
    return {
        "statusCode": 200,
        "body": json.dumps({"status": "valid"})
    }
```
