Skip to content

AI Gateway

概要とメリット

  • AI Gatewayは、複数のAIモデルプロバイダー(OpenAI、Azure OpenAI、IBM watsonx.aiなど)への統一されたアクセスポイントを提供し、AIモデルの利用を一元管理できます。
  • コスト管理、レート制限、セキュリティポリシーの適用、使用状況の監視など、エンタープライズグレードのAI利用に必要な機能を提供します。
  • Instanaと統合することで、AIモデルの呼び出しパフォーマンス、エラー率、レスポンスタイムなどを可視化し、AI機能の品質を継続的に監視できます。

公式ドキュメントのリンク

公式ドキュメントで不足している情報

複数プロバイダーの優先順位設定

公式ドキュメントでは基本的な設定が中心ですが、実運用では複数のAIプロバイダーを使い分ける必要があります。

フォールバック設定の実装:

# ai-gateway-config.yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: ai-gateway-config
  namespace: ai-gateway
data:
  config.yaml: |
    providers:
      - name: primary
        type: openai
        endpoint: https://api.openai.com/v1
        api_key: ${OPENAI_API_KEY}
        models:
          - gpt-4
          - gpt-3.5-turbo
        priority: 1
        max_requests_per_minute: 100

      - name: secondary
        type: azure-openai
        endpoint: https://your-resource.openai.azure.com
        api_key: ${AZURE_OPENAI_API_KEY}
        models:
          - gpt-4
          - gpt-35-turbo
        priority: 2
        max_requests_per_minute: 200

      - name: fallback
        type: watsonx
        endpoint: https://us-south.ml.cloud.ibm.com
        api_key: ${WATSONX_API_KEY}
        models:
          - ibm/granite-13b-chat-v2
        priority: 3
        max_requests_per_minute: 50

    routing:
      strategy: priority  # priority, round-robin, least-latency
      fallback_enabled: true
      fallback_on_errors:
        - rate_limit_exceeded
        - service_unavailable
        - timeout
      retry_attempts: 3
      retry_delay: 1s

動的なプロバイダー切り替え:

# アプリケーション側の実装例
import requests

def call_ai_gateway(prompt, model="gpt-4", prefer_provider=None):
    headers = {
        "Authorization": f"Bearer {AI_GATEWAY_TOKEN}",
        "Content-Type": "application/json"
    }

    payload = {
        "model": model,
        "messages": [{"role": "user", "content": prompt}],
        "prefer_provider": prefer_provider  # オプション: 優先プロバイダー
    }

    response = requests.post(
        "http://ai-gateway:8080/v1/chat/completions",
        headers=headers,
        json=payload,
        timeout=30
    )

    # レスポンスヘッダーで実際に使用されたプロバイダーを確認
    used_provider = response.headers.get("X-Provider-Used")
    print(f"Used provider: {used_provider}")

    return response.json()

コスト管理と予算アラート

公式ドキュメントでは触れられていませんが、AIモデルの利用コストは急速に増加する可能性があります。

コスト追跡の設定:

# ai-gateway-config.yaml に追加
cost_management:
  enabled: true
  currency: USD

  # プロバイダーごとのコスト設定
  provider_costs:
    openai:
      gpt-4:
        input_token_cost: 0.00003  # $0.03 per 1K tokens
        output_token_cost: 0.00006  # $0.06 per 1K tokens
      gpt-3.5-turbo:
        input_token_cost: 0.0000015
        output_token_cost: 0.000002

    azure-openai:
      gpt-4:
        input_token_cost: 0.00003
        output_token_cost: 0.00006

    watsonx:
      granite-13b-chat-v2:
        input_token_cost: 0.000001
        output_token_cost: 0.000001

  # 予算制限
  budgets:
    - name: daily-limit
      period: daily
      limit: 100.00
      alert_threshold: 0.8  # 80%で警告

    - name: monthly-limit
      period: monthly
      limit: 2000.00
      alert_threshold: 0.9

    - name: per-user-daily
      period: daily
      limit: 10.00
      scope: user

  # アラート設定
  alerts:
    - type: budget_threshold
      channels:
        - slack
        - email
    - type: cost_spike
      threshold: 2.0  # 通常の2倍のコスト
      channels:
        - slack

コスト監視ダッシュボードの作成:

# Prometheusメトリクスのエクスポート設定
# ai-gateway-config.yaml に追加
metrics:
  enabled: true
  port: 9090
  path: /metrics

  # カスタムメトリクス
  custom_metrics:
    - name: ai_gateway_cost_total
      type: counter
      labels:
        - provider
        - model
        - user

    - name: ai_gateway_tokens_total
      type: counter
      labels:
        - provider
        - model
        - type  # input/output

Grafanaダッシュボード用のクエリ例:

1
2
3
4
5
6
7
8
# 1時間あたりのコスト
rate(ai_gateway_cost_total[1h]) * 3600

# プロバイダー別のコスト分布
sum by (provider) (ai_gateway_cost_total)

# ユーザー別のトップ10
topk(10, sum by (user) (ai_gateway_cost_total))

セキュリティとアクセス制御

公式ドキュメントでは基本的な認証のみですが、エンタープライズ環境では詳細なアクセス制御が必要です。

ロールベースアクセス制御(RBAC):

# rbac-config.yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: ai-gateway-rbac
  namespace: ai-gateway
data:
  rbac.yaml: |
    roles:
      - name: admin
        permissions:
          - manage_providers
          - view_all_requests
          - manage_budgets
          - manage_users

      - name: developer
        permissions:
          - use_models
          - view_own_requests
          - view_costs
        limits:
          max_requests_per_day: 1000
          max_cost_per_day: 50.00
          allowed_models:
            - gpt-3.5-turbo
            - granite-13b-chat-v2

      - name: data-scientist
        permissions:
          - use_models
          - view_own_requests
          - view_costs
          - fine_tune_models
        limits:
          max_requests_per_day: 5000
          max_cost_per_day: 200.00
          allowed_models:
            - gpt-4
            - gpt-3.5-turbo
            - granite-13b-chat-v2

      - name: readonly
        permissions:
          - view_own_requests
        limits:
          max_requests_per_day: 100
          max_cost_per_day: 5.00
          allowed_models:
            - gpt-3.5-turbo

    users:
      - username: alice@example.com
        role: data-scientist
        api_key: ${ALICE_API_KEY}

      - username: bob@example.com
        role: developer
        api_key: ${BOB_API_KEY}

      - username: charlie@example.com
        role: readonly
        api_key: ${CHARLIE_API_KEY}

APIキーの管理:

# APIキーの生成
kubectl exec -it ai-gateway-0 -n ai-gateway -- \
  ai-gateway-cli create-api-key \
    --user alice@example.com \
    --role data-scientist \
    --expires-in 90d

# APIキーのローテーション
kubectl exec -it ai-gateway-0 -n ai-gateway -- \
  ai-gateway-cli rotate-api-key \
    --user alice@example.com \
    --grace-period 7d

# APIキーの無効化
kubectl exec -it ai-gateway-0 -n ai-gateway -- \
  ai-gateway-cli revoke-api-key \
    --user alice@example.com

Instanaとの統合設定

公式ドキュメントでは基本的な統合のみですが、詳細な監視には追加設定が必要です。

カスタムメトリクスの送信:

# ai-gateway-config.yaml に追加
instana:
  enabled: true
  agent_host: instana-agent.instana-agent.svc.cluster.local
  agent_port: 42699

  # カスタムメトリクス
  custom_metrics:
    - name: ai_request_duration
      type: histogram
      buckets: [0.1, 0.5, 1.0, 2.0, 5.0, 10.0]
      labels:
        - provider
        - model
        - status

    - name: ai_token_count
      type: histogram
      buckets: [100, 500, 1000, 2000, 5000, 10000]
      labels:
        - provider
        - model
        - type  # input/output

    - name: ai_cost_per_request
      type: histogram
      buckets: [0.001, 0.01, 0.1, 1.0, 10.0]
      labels:
        - provider
        - model

  # トレース設定
  tracing:
    enabled: true
    sample_rate: 1.0  # 100%サンプリング
    include_request_body: false  # プライバシー保護
    include_response_body: false

  # タグ付け
  tags:
    service: ai-gateway
    environment: production
    team: ai-platform

アラート設定:

# instana-alerts.yaml
alerts:
  - name: AI Gateway High Error Rate
    condition:
      metric: ai_gateway_errors_total
      threshold: 10
      window: 5m
    actions:
      - type: slack
        channel: "#ai-alerts"
      - type: pagerduty
        service: ai-gateway

  - name: AI Gateway High Latency
    condition:
      metric: ai_request_duration
      percentile: p95
      threshold: 5.0  # 5秒
      window: 5m
    actions:
      - type: slack
        channel: "#ai-alerts"

  - name: AI Gateway Budget Alert
    condition:
      metric: ai_gateway_cost_total
      threshold: 80  # 予算の80%
      window: 1d
    actions:
      - type: email
        recipients:
          - finance@example.com
          - ai-team@example.com

具体的なユースケース

ユースケース1: マルチプロバイダー環境でのコスト最適化

背景・課題: 複数のAIプロバイダーを利用しているが、コストが予想以上に増加している。どのプロバイダーが最もコスト効率が良いか判断したい。

解決方法: AI Gatewayでコスト追跡を有効にし、Instanaで可視化してコスト最適化を実施。

手順:

  1. 現状のコスト分析

Instana UIでカスタムダッシュボードを作成:

1
2
3
4
- プロバイダー別のコスト推移
- モデル別のコスト分布
- ユーザー別のコスト消費
- リクエストあたりの平均コスト

  1. コスト効率の比較

各プロバイダーのコストパフォーマンスを分析:

OpenAI GPT-4:
- 平均レスポンスタイム: 2.3秒
- リクエストあたりコスト: $0.05
- エラー率: 0.5%

Azure OpenAI GPT-4:
- 平均レスポンスタイム: 2.1秒
- リクエストあたりコスト: $0.05
- エラー率: 0.3%

watsonx Granite:
- 平均レスポンスタイム: 1.8秒
- リクエストあたりコスト: $0.002
- エラー率: 1.2%

  1. ルーティング戦略の最適化
# 用途別のルーティング設定
routing:
  rules:
    # 高精度が必要なタスク → GPT-4
    - name: high-accuracy
      condition:
        tags:
          - critical
          - customer-facing
      providers:
        - openai-gpt4
        - azure-openai-gpt4

    # 一般的なタスク → コスト効率重視
    - name: general
      condition:
        tags:
          - internal
          - batch-processing
      providers:
        - watsonx-granite
        - openai-gpt35

    # 大量処理 → 最もコスト効率の良いプロバイダー
    - name: bulk
      condition:
        batch_size: ">100"
      providers:
        - watsonx-granite
  1. 効果測定

最適化後の結果: - 月間コスト: $5,000 → $2,800(44%削減) - 平均レスポンスタイム: 2.2秒 → 2.0秒(改善) - エラー率: 0.6% → 0.7%(許容範囲内)

期待される効果: - コスト削減: 44% - パフォーマンス維持または改善 - 用途に応じた最適なプロバイダー選択

ユースケース2: レート制限とフォールバック戦略

背景・課題: プライマリプロバイダー(OpenAI)のレート制限に頻繁に到達し、アプリケーションがエラーを返す。ユーザー体験が悪化している。

解決方法: AI Gatewayのフォールバック機能を活用し、レート制限時に自動的に別のプロバイダーに切り替え。

手順:

  1. 現状の問題を可視化

Instanaで以下を確認:

1
2
3
- レート制限エラーの発生頻度
- エラー発生時刻のパターン
- 影響を受けたリクエスト数

分析結果: - ピーク時(10:00-12:00)にレート制限エラーが集中 - 1日あたり約200件のリクエストが失敗 - ユーザーからの苦情が増加

  1. フォールバック戦略の実装
# ai-gateway-config.yaml
providers:
  - name: openai-primary
    type: openai
    priority: 1
    max_requests_per_minute: 100
    circuit_breaker:
      enabled: true
      failure_threshold: 5
      timeout: 30s
      reset_timeout: 60s

  - name: azure-openai-secondary
    type: azure-openai
    priority: 2
    max_requests_per_minute: 200
    circuit_breaker:
      enabled: true
      failure_threshold: 5
      timeout: 30s
      reset_timeout: 60s

  - name: watsonx-fallback
    type: watsonx
    priority: 3
    max_requests_per_minute: 50

routing:
  strategy: priority
  fallback_enabled: true
  fallback_on_errors:
    - rate_limit_exceeded
    - service_unavailable
    - timeout

  # サーキットブレーカー設定
  circuit_breaker:
    enabled: true
    failure_threshold: 5  # 5回連続失敗で開く
    success_threshold: 2  # 2回連続成功で閉じる
    timeout: 30s
    half_open_requests: 3
  1. 監視とアラート設定
# Instanaアラート
alerts:
  - name: Provider Failover
    condition:
      metric: ai_gateway_provider_failover_total
      threshold: 10
      window: 5m
    actions:
      - type: slack
        message: "AI Gateway failover detected: {{provider}}  {{fallback_provider}}"

  - name: Circuit Breaker Open
    condition:
      metric: ai_gateway_circuit_breaker_state
      value: open
    actions:
      - type: pagerduty
        severity: warning
  1. 効果測定

実装後の結果:

1
2
3
4
5
6
7
8
9
Before:
- 成功率: 92%
- レート制限エラー: 200件/日
- ユーザー苦情: 15件/週

After:
- 成功率: 99.5%
- レート制限エラー: 5件/日(フォールバック成功)
- ユーザー苦情: 1件/週

期待される効果: - 可用性の向上: 92% → 99.5% - ユーザー体験の改善 - レート制限の影響を最小化

ユースケース3: セキュリティとコンプライアンス対応

背景・課題: AIモデルに送信されるデータに個人情報が含まれる可能性があり、コンプライアンス要件を満たす必要がある。

解決方法: AI Gatewayでデータマスキングとアクセス制御を実装し、コンプライアンスを確保。

手順:

  1. データマスキングの実装
# ai-gateway-config.yaml
security:
  data_masking:
    enabled: true

    # PII検出と自動マスキング
    pii_detection:
      enabled: true
      patterns:
        - type: email
          regex: '\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b'
          replacement: '[EMAIL]'

        - type: phone
          regex: '\b\d{3}[-.]?\d{3}[-.]?\d{4}\b'
          replacement: '[PHONE]'

        - type: ssn
          regex: '\b\d{3}-\d{2}-\d{4}\b'
          replacement: '[SSN]'

        - type: credit_card
          regex: '\b\d{4}[-\s]?\d{4}[-\s]?\d{4}[-\s]?\d{4}\b'
          replacement: '[CARD]'

    # ログからの除外
    exclude_from_logs:
      - request_body
      - response_body

    # 監査ログの保持
    audit_log:
      enabled: true
      retention_days: 90
      include_masked_data: false
  1. アクセス制御の強化
# rbac-config.yaml
compliance:
  gdpr:
    enabled: true
    data_residency: eu-west-1
    consent_required: true

  hipaa:
    enabled: true
    encryption_at_rest: true
    encryption_in_transit: true
    audit_logging: true

access_control:
  # IPホワイトリスト
  ip_whitelist:
    enabled: true
    allowed_ips:
      - 10.0.0.0/8
      - 172.16.0.0/12

  # 地理的制限
  geo_restriction:
    enabled: true
    allowed_countries:
      - US
      - JP
      - EU

  # 時間ベースのアクセス制御
  time_based_access:
    enabled: true
    allowed_hours:
      start: "06:00"
      end: "22:00"
      timezone: "Asia/Tokyo"
  1. 監査とコンプライアンスレポート
# 監査ログの分析スクリプト
import pandas as pd
from datetime import datetime, timedelta

def generate_compliance_report(start_date, end_date):
    # AI Gatewayの監査ログを取得
    logs = fetch_audit_logs(start_date, end_date)

    report = {
        "total_requests": len(logs),
        "pii_detected": logs[logs['pii_detected'] == True].shape[0],
        "masked_requests": logs[logs['data_masked'] == True].shape[0],
        "unauthorized_attempts": logs[logs['status'] == 'unauthorized'].shape[0],
        "geo_blocked": logs[logs['geo_blocked'] == True].shape[0],
        "users": logs['user'].nunique(),
        "models_used": logs['model'].value_counts().to_dict()
    }

    return report

# 月次レポートの生成
report = generate_compliance_report(
    start_date=datetime.now() - timedelta(days=30),
    end_date=datetime.now()
)
  1. Instanaでのコンプライアンス監視
# カスタムダッシュボード
dashboards:
  - name: Compliance Dashboard
    widgets:
      - type: metric
        title: PII Detection Rate
        query: rate(ai_gateway_pii_detected_total[1h])

      - type: metric
        title: Data Masking Success Rate
        query: |
          ai_gateway_data_masked_total / 
          ai_gateway_pii_detected_total * 100

      - type: table
        title: Unauthorized Access Attempts
        query: ai_gateway_unauthorized_attempts
        columns:
          - user
          - ip_address
          - timestamp
          - reason

期待される効果: - コンプライアンス要件の充足 - PIIの自動検出とマスキング - 監査証跡の完全な記録 - セキュリティインシデントの早期検出

実運用での注意点・ベストプラクティス

プロバイダーの健全性監視

各AIプロバイダーの状態を継続的に監視し、問題を早期に検出:

# ヘルスチェック設定
health_checks:
  enabled: true
  interval: 30s
  timeout: 10s

  providers:
    - name: openai
      endpoint: https://api.openai.com/v1/models
      expected_status: 200

    - name: azure-openai
      endpoint: https://your-resource.openai.azure.com/openai/deployments
      expected_status: 200

    - name: watsonx
      endpoint: https://us-south.ml.cloud.ibm.com/ml/v4/models
      expected_status: 200

キャッシング戦略

同じリクエストに対してキャッシュを活用し、コストとレイテンシを削減:

caching:
  enabled: true
  backend: redis
  redis:
    host: redis.ai-gateway.svc.cluster.local
    port: 6379
    db: 0

  # キャッシュ戦略
  strategy:
    ttl: 3600  # 1時間
    max_size: 10000  # 最大10,000エントリ

    # キャッシュキーの生成
    key_components:
      - model
      - prompt_hash
      - temperature
      - max_tokens

    # キャッシュ対象の条件
    cache_conditions:
      - temperature: 0  # 決定的な出力のみキャッシュ
      - max_tokens: "<1000"

段階的なロールアウト

新しいプロバイダーやモデルを段階的に導入:

# カナリアデプロイメント
canary:
  enabled: true

  # 新しいプロバイダーのテスト
  - name: test-new-provider
    provider: new-provider
    traffic_percentage: 5  # 5%のトラフィックのみ
    duration: 7d

    # 成功条件
    success_criteria:
      error_rate: "<1%"
      latency_p95: "<3s"
      cost_increase: "<10%"

    # 自動ロールバック条件
    rollback_on:
      error_rate: ">5%"
      latency_p95: ">5s"

よくあるトラブルと解決方法

プロバイダーへの接続が頻繁に失敗する

症状: 特定のAIプロバイダーへの接続が断続的に失敗し、フォールバックが頻繁に発生する。

原因: ネットワークの不安定性、タイムアウト設定の不適切、またはプロバイダー側の問題。

解決方法:

# 1. ネットワーク接続の確認
kubectl exec -it ai-gateway-0 -n ai-gateway -- \
  curl -v https://api.openai.com/v1/models

# 2. DNSの確認
kubectl exec -it ai-gateway-0 -n ai-gateway -- \
  nslookup api.openai.com

# 3. タイムアウト設定の調整
kubectl edit configmap ai-gateway-config -n ai-gateway

# timeout: 30s → 60s に変更

# 4. リトライ設定の最適化
# ai-gateway-config.yaml
providers:
  - name: openai
    retry:
      max_attempts: 3
      initial_delay: 1s
      max_delay: 10s
      multiplier: 2
      jitter: 0.1

    timeout:
      connect: 10s
      read: 60s
      write: 30s

コストが予算を超過する

症状: AIモデルの利用コストが予算を大幅に超過し、アラートが頻発する。

原因: 予期しない大量リクエスト、高コストなモデルの過度な使用、またはコスト設定の誤り。

解決方法:

# 1. コスト分析
kubectl exec -it ai-gateway-0 -n ai-gateway -- \
  ai-gateway-cli cost-report --period 7d --group-by user,model

# 2. 高コストユーザーの特定
kubectl exec -it ai-gateway-0 -n ai-gateway -- \
  ai-gateway-cli top-users --metric cost --limit 10

# 3. 緊急のレート制限適用
kubectl exec -it ai-gateway-0 -n ai-gateway -- \
  ai-gateway-cli set-rate-limit \
    --user high-cost-user@example.com \
    --limit 100 \
    --period 1h
# 恒久的な対策
cost_management:
  budgets:
    - name: emergency-limit
      period: daily
      limit: 50.00
      hard_limit: true  # 予算超過時にリクエストを拒否

  # 自動スケールダウン
  auto_throttle:
    enabled: true
    trigger_threshold: 0.9  # 予算の90%
    throttle_percentage: 50  # リクエストを50%に制限

レスポンスタイムが遅い

症状: AIモデルからのレスポンスが遅く、アプリケーションのパフォーマンスが低下している。

原因: プロバイダーの負荷、ネットワークレイテンシ、または非効率なルーティング。

解決方法:

1
2
3
4
5
6
7
# 1. レイテンシの分析
# Instana UIで以下を確認:
# - プロバイダー別のレスポンスタイム
# - ネットワークレイテンシ
# - キューイング時間

# 2. 最速プロバイダーへの自動ルーティング
# ai-gateway-config.yaml
routing:
  strategy: least-latency  # 最もレイテンシの低いプロバイダーを選択

  latency_tracking:
    enabled: true
    window: 5m
    sample_size: 100

  # レイテンシベースのフォールバック
  latency_threshold: 3s
  fallback_on_slow_response: true
# 3. 非同期処理の実装
import asyncio
import aiohttp

async def call_ai_async(prompts):
    async with aiohttp.ClientSession() as session:
        tasks = [
            session.post(
                "http://ai-gateway:8080/v1/chat/completions",
                json={"model": "gpt-3.5-turbo", "messages": [{"role": "user", "content": p}]}
            )
            for p in prompts
        ]
        responses = await asyncio.gather(*tasks)
        return [await r.json() for r in responses]

# バッチ処理で複数のリクエストを並列実行
results = asyncio.run(call_ai_async(prompts))

期待される効果: - レスポンスタイム: 5秒 → 2秒(60%改善) - スループット: 2倍に向上 - ユーザー体験の改善