# API Normalization Gateway

Provides API Gateway capabilities including request/response transformation, routing, rate limiting, and multi-provider orchestration.

## Overview

An API Gateway acts as a single entry point for API requests, handling transformation, routing, rate limiting, and aggregation across multiple providers. This module extends the api_normalization core with enterprise-grade gateway features.

## Why Use This Module?

### The Problem

```php
// Without gateway: Direct provider calls with manual handling
$provider = 'anthropic';
$request = transformRequestForProvider($openai_request, $provider);
$response = callProvider($request, $provider);
$openai_response = transformResponseFromProvider($response, $provider);
```

### The Solution

```php
// With gateway: Single endpoint, automatic transformation
POST /api/gateway/chat
{
  "model": "gpt-4",
  "messages": [...]
}

// Gateway handles everything:
// 1. Validates request
// 2. Routes to best provider
// 3. Transforms request
// 4. Makes call
// 5. Transforms response
// 6. Returns OpenAI-compatible result
```

## Features

### 1. Request/Response Transformation
- Accepts OpenAI-formatted requests
- Transforms to provider-specific format
- Transforms responses back to OpenAI format
- Works with any provider supported by drupal/ai

### 2. Intelligent Routing
- Route to best available provider
- Failover-aware routing (integrates with failover module)
- Load balancing across providers
- Provider health checks

### 3. Rate Limiting
- Per-provider rate limits
- Per-user quotas
- Token-based throttling
- Burst allowance

### 4. Request Aggregation
- Multi-provider consensus
- Parallel execution
- Response comparison
- Majority voting

## Installation

```bash
drush en api_normalization_gateway
```

## Configuration

### Gateway Routes

Configure routes at: **Configuration > API Normalization > Gateway Routes**

```yaml
# config/install/api_normalization_gateway.routes.yml
chat:
  path: /api/gateway/chat
  methods: [POST]
  providers: [anthropic, openai, ollama]
  default_provider: anthropic
  fallback_enabled: true

embeddings:
  path: /api/gateway/embeddings
  methods: [POST]
  providers: [openai, ollama]
  default_provider: openai
```

### Rate Limiting

```yaml
rate_limits:
  anthropic:
    requests_per_minute: 60
    tokens_per_minute: 100000
    burst: 10

  openai:
    requests_per_minute: 90
    tokens_per_minute: 150000
```

## Usage

### Basic Gateway Request

```bash
curl -X POST http://your-site.com/api/gateway/chat \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gpt-4",
    "messages": [
      {"role": "user", "content": "Hello!"}
    ]
  }'
```

Response (always OpenAI format):
```json
{
  "choices": [
    {
      "message": {
        "role": "assistant",
        "content": "Hello! How can I help you today?"
      },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 10,
    "completion_tokens": 12,
    "total_tokens": 22
  },
  "provider_used": "anthropic"
}
```

### Multi-Provider Consensus

```php
$gateway = \Drupal::service('api_normalization.gateway');

$result = $gateway->multiProviderRequest([
  'providers' => ['anthropic', 'openai', 'cohere'],
  'consensus_strategy' => 'majority',
  'messages' => $messages,
]);

// Returns most common response from 3 providers
```

### Custom Transformation

```php
$gateway = \Drupal::service('api_normalization.gateway');

$gateway->addTransformationRule('custom_provider', [
  'request' => function($openai_request) {
    return ['custom_format' => $openai_request['messages']];
  },
  'response' => function($custom_response) {
    return ['choices' => [['message' => ['content' => $custom_response['data']]]]];
  },
]);
```

## Gateway Features

### Load Balancing

```yaml
load_balancing:
  strategy: round_robin  # or: least_latency, random, weighted
  providers:
    - anthropic: {weight: 3}
    - openai: {weight: 2}
    - ollama: {weight: 1}
```

### Health Checks

```yaml
health_checks:
  enabled: true
  interval: 60  # seconds
  timeout: 5
  failure_threshold: 3
```

### Caching

```yaml
caching:
  enabled: true
  ttl: 3600
  cache_key_strategy: hash_request
  exclude_providers: [ollama]  # Don't cache local
```

## API Documentation

### Gateway Service

```php
interface ApiGatewayManagerInterface {
  
  /**
   * Route request to appropriate provider.
   */
  public function routeRequest(array $request, array $options = []): array;

  /**
   * Execute multi-provider request.
   */
  public function multiProviderRequest(array $config): array;

  /**
   * Get gateway statistics.
   */
  public function getStatistics(): array;
}
```

## Permissions

- **Access API gateway**: Make requests to gateway endpoints
- **Configure gateway routes**: Add/edit gateway routes
- **View gateway metrics**: Access statistics and logs
- **Administer API gateway**: Full administrative access

## Troubleshooting

### Gateway Returns 404

**Solution**:
```bash
drush cr  # Rebuild routes
drush cget api_normalization_gateway.routes  # Verify routes
```

### Rate Limit Exceeded

**Solution**:
```yaml
# Increase limits or add more providers
rate_limits:
  anthropic:
    requests_per_minute: 120  # Increased
```

### All Providers Failing

**Solution**: Check gateway status and failover configuration
```bash
drush api-norm:gateway-status
drush api-norm:test-failover anthropic
```

## Dependencies

- **drupal/api_normalization** (required)
- **drupal/ai** (required)

## See Also

- [API Normalization README](../../README.md)
- [Failover Module](../api_normalization_failover/README.md)
- [Tamper Module](../api_normalization_tamper/README.md)

## Maintainers

See [main module README](../../README.md#maintainers).
