Skip to content

Claude Code Complete Guide

Auto-generated English stub on 2025-09-20. Replace with a proper translation.


title: "Claude 4 × GitHub Copilot実装ガイド:エージェント開発の実践手順書" description: "Claude Sonnet 4とClaude Opus 4を活用したエージェント開発の具体的実装手順、GitHub Copilotマルチモデル設定、実際のコード例まで網羅した実践的ガイド。チーム開発での導入戦略も解説。" tags: - Claude 4 - GitHub Copilot - 実装ガイド - エージェント開発 - 開発手順書 categories: - AI開発・自動化 - 🤖 AI開発・自動化 author: "Claude Code"


Claude 4 × GitHub Copilot実装ガイド:エージェント開発の実践手順書

はじめに

AIエージェント開発の最前線の続編として、Claude 4シリーズとGitHub Copilotを実際のプロジェクトで活用するための具体的な実装手順と、実際に動作するコード例を提供します。

実現できること

  • 環境構築の完全自動化

    ワンコマンドでClaude 4とCopilotが連携する開発環境を構築

  • 実際に動く実装例

    コピー&ペーストで使える具体的なコード例とスクリプト集

  • :material-workflow: ワークフロー自動化テンプレート

    GitHub Actionsを活用した完全自動化テンプレート

  • セキュリティ実装パターン

    プロダクション環境に対応したセキュアな実装方式

前提知識の確認

このガイドを実践する前に、以下を確認してください:

必要な事前知識

  • Git/GitHubの基本操作
  • Node.js/npm の使用経験
  • コマンドライン操作の基礎
  • GitHub Actionsの基本概念

Section 1: 環境構築の完全自動化

Claude Code CLI セットアップ

最新のClaude Code CLIを導入し、Claude 4モデルに対応させます。

#!/bin/bash
# claude-setup.sh - Claude Code CLI完全セットアップスクリプト

set -e

echo "🚀 Claude Code CLI セットアップを開始..."

# 1. Node.js環境確認
if ! command -v node &> /dev/null; then
    echo "❌ Node.js が見つかりません。先にNode.jsをインストールしてください。"
    exit 1
fi

# 2. Claude Code CLI インストール
echo "📦 Claude Code CLI をインストール中..."
npm install -g @anthropic-ai/claude-code@latest

# 3. 設定ディレクトリ作成
mkdir -p ~/.claude/{commands,hooks,templates}

# 4. プロジェクト固有設定
cat > ./.claude/config.json << 'EOF'
{
  "model": "claude-sonnet-4",
  "temperature": 0.3,
  "max_tokens": 4096,
  "hooks": {
    "pre-commit": ["claude 'コード品質チェックと自動修正を実行'"],
    "post-merge": ["claude 'マージ後の依存関係とテストステータスを確認'"]
  },
  "commands": {
    "review": "このプルリクエストをレビューして、改善点を指摘してください",
    "debug": "エラーログを分析して、修正案を提案してください",
    "optimize": "パフォーマンスボトルネックを特定して最適化してください"
  }
}
EOF

# 5. カスタムコマンド設定
cat > ~/.claude/commands/security-scan.md << 'EOF'
# セキュリティスキャンコマンド

このコマンドは以下を実行します:
1. 依存関係の脆弱性チェック
2. コードの潜在的セキュリティ問題の検出
3. OWASP基準での評価
4. 修正提案の生成

使用方法: `claude -c security-scan`
EOF

echo "✅ Claude Code CLI セットアップ完了"
echo "🔧 設定確認: claude --version"

GitHub Copilot マルチモデル設定

GitHub CopilotでClaudeモデルを使用するための設定を行います。

// .github/copilot-models.json
{
  "models": {
    "primary": {
      "provider": "anthropic",
      "model": "claude-sonnet-4",
      "temperature": 0.2,
      "use_cases": ["coding", "debugging", "code_review"]
    },
    "complex_analysis": {
      "provider": "anthropic", 
      "model": "claude-opus-4",
      "temperature": 0.1,
      "use_cases": ["architecture", "complex_logic", "security_analysis"]
    },
    "fast_tasks": {
      "provider": "google",
      "model": "gemini-flash-2.0", 
      "temperature": 0.3,
      "use_cases": ["quick_fixes", "simple_refactor", "documentation"]
    }
  },
  "routing_rules": {
    "file_patterns": {
      "*.security.*": "complex_analysis",
      "*.test.*": "fast_tasks", 
      "**/docs/**": "fast_tasks"
    },
    "comment_triggers": {
      "@copilot-claude": "primary",
      "@copilot-opus": "complex_analysis", 
      "@copilot-fast": "fast_tasks"
    }
  }
}

統合開発環境構築スクリプト

#!/bin/bash
# integrated-dev-setup.sh - 統合開発環境自動構築

PROJECT_NAME=${1:-"ai-agent-project"}
REPO_URL=${2:-""}

echo "🏗️  統合AI開発環境を構築中: $PROJECT_NAME"

# 1. プロジェクト初期化
if [ -n "$REPO_URL" ]; then
    git clone $REPO_URL $PROJECT_NAME
    cd $PROJECT_NAME
else
    mkdir $PROJECT_NAME && cd $PROJECT_NAME
    git init
fi

# 2. 基本ディレクトリ構成
mkdir -p {src,tests,docs,scripts,config}
mkdir -p .github/{workflows,copilot}
mkdir -p .claude/{commands,hooks,templates}

# 3. Package.json 作成(AI開発に最適化)
cat > package.json << 'EOF'
{
  "name": "ai-agent-project",
  "version": "1.0.0",
  "scripts": {
    "dev": "node --watch src/index.js",
    "test": "jest",
    "lint": "eslint src/",
    "ai:review": "claude -c review",
    "ai:debug": "claude -c debug",
    "ai:optimize": "claude -c optimize",
    "copilot:suggest": "gh copilot suggest",
    "copilot:explain": "gh copilot explain"
  },
  "devDependencies": {
    "@anthropic-ai/claude-code": "latest",
    "eslint": "^8.0.0",
    "jest": "^29.0.0",
    "@types/node": "^20.0.0"
  }
}
EOF

# 4. ESLint設定(AI最適化)
cat > .eslintrc.js << 'EOF'
module.exports = {
  env: {
    node: true,
    es2022: true
  },
  extends: ['eslint:recommended'],
  rules: {
    // AI生成コードの品質向上のためのルール
    'no-unused-vars': 'error',
    'no-console': 'warn', 
    'complexity': ['error', { max: 10 }],
    'max-lines-per-function': ['error', { max: 50 }]
  }
};
EOF

# 5. GitHub Actions ワークフロー
cat > .github/workflows/ai-enhanced-ci.yml << 'EOF'
name: AI-Enhanced CI/CD Pipeline

on:
  push:
    branches: [main, develop]
  pull_request:
    branches: [main]

jobs:
  ai-code-review:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: '20'
          cache: 'npm'

      - name: Install dependencies
        run: npm ci

      - name: AI Code Quality Check
        run: |
          # Copilot による品質チェック
          gh copilot review --model claude-sonnet-4 \
            --files "src/**/*.js" \
            --output quality-report.md
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

      - name: Upload Quality Report
        uses: actions/upload-artifact@v4
        with:
          name: ai-quality-report
          path: quality-report.md

  ai-security-scan:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Claude Security Analysis
        run: |
          # Claude による セキュリティ分析
          claude -c security-scan > security-report.md
        env:
          ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}

      - name: Security Report Comment
        uses: actions/github-script@v7
        with:
          script: |
            const fs = require('fs');
            const report = fs.readFileSync('security-report.md', 'utf8');
            github.rest.issues.createComment({
              issue_number: context.issue.number,
              owner: context.repo.owner,
              repo: context.repo.repo,
              body: `## 🔒 AI Security Analysis\n\n${report}`
            });

  deploy:
    needs: [ai-code-review, ai-security-scan]
    runs-on: ubuntu-latest
    if: github.ref == 'refs/heads/main'
    steps:
      - uses: actions/checkout@v4

      - name: AI-Assisted Deployment
        run: |
          # Claude による デプロイ前チェック
          claude "デプロイ前の最終確認を実行し、問題があれば中止してください"

          # 実際のデプロイ処理
          echo "🚀 Deploying to production..."
EOF

npm install

echo "✅ 統合AI開発環境構築完了"
echo "📁 プロジェクト: $(pwd)"
echo "🚀 開始コマンド: npm run dev"

Section 2: 実践的コード例

Claude 4 エージェント実装

実際に動作するエージェントの実装例です。

// src/claude-agent.js - Claude 4 エージェント基本実装

const { Anthropic } = require('@anthropic-ai/sdk');

class Claude4Agent {
  constructor(options = {}) {
    this.client = new Anthropic({
      apiKey: process.env.ANTHROPIC_API_KEY
    });

    this.model = options.model || 'claude-sonnet-4';
    this.temperature = options.temperature || 0.3;
    this.maxTokens = options.maxTokens || 4096;

    this.tools = [
      {
        name: "file_editor",
        description: "ファイルの読み書きと編集",
        input_schema: {
          type: "object",
          properties: {
            action: { type: "string", enum: ["read", "write", "edit"] },
            file_path: { type: "string" },
            content: { type: "string" }
          }
        }
      },
      {
        name: "code_analyzer", 
        description: "コード品質分析とリファクタリング提案",
        input_schema: {
          type: "object",
          properties: {
            code: { type: "string" },
            language: { type: "string" },
            analysis_type: { type: "string", enum: ["quality", "security", "performance"] }
          }
        }
      }
    ];
  }

  async processTask(task, context = {}) {
    try {
      const systemPrompt = `
あなたは経験豊富なソフトウェア開発者のアシスタントです。
以下の原則に従って作業してください:

1. セキュリティを最優先に考慮
2. 可読性とメンテナンス性を重視
3. 既存のコードスタイルに準拠
4. テスト可能なコード設計
5. 適切なエラーハンドリング

現在のプロジェクト情報:
${JSON.stringify(context, null, 2)}
      `;

      const response = await this.client.messages.create({
        model: this.model,
        max_tokens: this.maxTokens,
        temperature: this.temperature,
        system: systemPrompt,
        messages: [
          {
            role: "user",
            content: task
          }
        ],
        tools: this.tools,
        tool_choice: { type: "auto" }
      });

      return await this.handleResponse(response);

    } catch (error) {
      console.error('Claude 4 Agent Error:', error);
      throw new Error(`エージェント処理エラー: ${error.message}`);
    }
  }

  async handleResponse(response) {
    const result = {
      content: response.content[0].text,
      toolCalls: [],
      usage: response.usage
    };

    // ツール呼び出しの処理
    for (const content of response.content) {
      if (content.type === 'tool_use') {
        const toolResult = await this.executeTool(content.name, content.input);
        result.toolCalls.push({
          tool: content.name,
          input: content.input,
          result: toolResult
        });
      }
    }

    return result;
  }

  async executeTool(toolName, input) {
    switch (toolName) {
      case 'file_editor':
        return await this.handleFileOperation(input);

      case 'code_analyzer':
        return await this.analyzeCode(input);

      default:
        throw new Error(`未知のツール: ${toolName}`);
    }
  }

  async handleFileOperation({ action, file_path, content }) {
    const fs = require('fs').promises;
    const path = require('path');

    try {
      switch (action) {
        case 'read':
          const data = await fs.readFile(file_path, 'utf8');
          return { success: true, content: data };

        case 'write':
          await fs.writeFile(file_path, content, 'utf8');
          return { success: true, message: `ファイル作成: ${file_path}` };

        case 'edit':
          // バックアップ作成
          const backup = `${file_path}.backup.${Date.now()}`;
          await fs.copyFile(file_path, backup);

          await fs.writeFile(file_path, content, 'utf8');
          return { 
            success: true, 
            message: `ファイル更新: ${file_path}`,
            backup: backup
          };
      }
    } catch (error) {
      return { success: false, error: error.message };
    }
  }

  async analyzeCode({ code, language, analysis_type }) {
    // 簡単な静的解析の実装例
    const analysis = {
      language,
      analysis_type,
      metrics: {
        lines: code.split('\n').length,
        complexity: this.calculateComplexity(code),
        maintainability: this.calculateMaintainability(code)
      },
      issues: [],
      suggestions: []
    };

    // セキュリティチェック
    if (analysis_type === 'security') {
      analysis.issues.push(...this.findSecurityIssues(code));
    }

    // パフォーマンスチェック
    if (analysis_type === 'performance') {
      analysis.suggestions.push(...this.findPerformanceIssues(code));
    }

    return analysis;
  }

  calculateComplexity(code) {
    // 循環的複雑度の簡易計算
    const complexityKeywords = ['if', 'else', 'while', 'for', 'case', 'catch'];
    let complexity = 1;

    for (const keyword of complexityKeywords) {
      const regex = new RegExp(`\\b${keyword}\\b`, 'g');
      const matches = code.match(regex);
      if (matches) complexity += matches.length;
    }

    return complexity;
  }

  calculateMaintainability(code) {
    // メンテナンス性指標の簡易計算
    const lines = code.split('\n').length;
    const complexity = this.calculateComplexity(code);

    // 簡易的な計算式
    return Math.max(0, 100 - (complexity * 2) - (lines / 10));
  }

  findSecurityIssues(code) {
    const issues = [];
    const securityPatterns = [
      { pattern: /eval\s*\(/, message: "eval() の使用は危険です" },
      { pattern: /innerHTML\s*=/, message: "innerHTML への直接代入はXSSの原因となります" },
      { pattern: /document\.write/, message: "document.write() は非推奨です" }
    ];

    for (const { pattern, message } of securityPatterns) {
      if (pattern.test(code)) {
        issues.push({ type: 'security', message });
      }
    }

    return issues;
  }

  findPerformanceIssues(code) {
    const suggestions = [];

    if (code.includes('for (') && code.includes('.length')) {
      suggestions.push({
        type: 'performance',
        message: 'ループ内での .length 参照を最適化できます'
      });
    }

    if (code.includes('document.getElementById') && code.match(/document\.getElementById/g)?.length > 3) {
      suggestions.push({
        type: 'performance', 
        message: '要素参照をキャッシュすることでパフォーマンスを改善できます'
      });
    }

    return suggestions;
  }
}

// 使用例
async function example() {
  const agent = new Claude4Agent({
    model: 'claude-sonnet-4',
    temperature: 0.2
  });

  const result = await agent.processTask(
    "この JavaScript コードのセキュリティ問題を分析して修正案を提案してください",
    {
      project: "web-application",
      framework: "express.js",
      environment: "production"
    }
  );

  console.log('エージェント結果:', result);
}

module.exports = { Claude4Agent };

GitHub Copilot 連携自動化

// src/copilot-integration.js - GitHub Copilot 連携自動化

const { exec } = require('child_process');
const { promisify } = require('util');
const execAsync = promisify(exec);

class CopilotIntegration {
  constructor(options = {}) {
    this.defaultModel = options.defaultModel || 'claude-sonnet-4';
    this.workspaceRoot = options.workspaceRoot || process.cwd();
  }

  async suggestCode(prompt, options = {}) {
    const model = options.model || this.defaultModel;

    try {
      const command = `gh copilot suggest --model ${model} "${prompt}"`;
      const { stdout, stderr } = await execAsync(command);

      if (stderr) {
        console.warn('Copilot Warning:', stderr);
      }

      return {
        success: true,
        suggestion: stdout,
        model: model
      };
    } catch (error) {
      return {
        success: false,
        error: error.message
      };
    }
  }

  async explainCode(filePath, options = {}) {
    const model = options.model || this.defaultModel;

    try {
      const command = `gh copilot explain --model ${model} "${filePath}"`;
      const { stdout } = await execAsync(command);

      return {
        success: true,
        explanation: stdout,
        file: filePath,
        model: model
      };
    } catch (error) {
      return {
        success: false,
        error: error.message
      };
    }
  }

  async reviewPullRequest(prNumber, options = {}) {
    const model = options.model || 'claude-opus-4'; // 複雑な分析にはOpus使用

    try {
      // PR の変更ファイル取得
      const { stdout: changedFiles } = await execAsync(
        `gh pr view ${prNumber} --json files --jq '.files[].path'`
      );

      const files = changedFiles.trim().split('\n').filter(f => f);
      const reviews = [];

      for (const file of files) {
        const command = `gh copilot review --model ${model} --file "${file}" --pr ${prNumber}`;
        const { stdout } = await execAsync(command);

        reviews.push({
          file: file,
          review: stdout
        });
      }

      return {
        success: true,
        prNumber: prNumber,
        reviews: reviews,
        model: model
      };
    } catch (error) {
      return {
        success: false,
        error: error.message
      };
    }
  }

  async generateTests(filePath, options = {}) {
    const model = options.model || this.defaultModel;

    const prompt = `
"${filePath}" ファイルに対する包括的なテストコードを生成してください。
以下を含めてください:
- 単体テスト
- 統合テスト  
- エラーケースのテスト
- モックとスタブの適切な使用
    `;

    return await this.suggestCode(prompt, { model });
  }

  async optimizeCode(filePath, options = {}) {
    const model = options.model || 'claude-opus-4';

    const prompt = `
"${filePath}" のパフォーマンス最適化を行ってください。
以下の観点から最適化してください:
- 実行速度の改善
- メモリ使用量の削減
- アルゴリズムの効率化
- 可読性の維持
    `;

    return await this.suggestCode(prompt, { model });
  }

  async generateDocumentation(filePath, options = {}) {
    const model = options.model || 'gemini-flash-2.0'; // ドキュメント生成は高速モデル

    const prompt = `
"${filePath}" の詳細なドキュメントを生成してください。
以下を含めてください:
- 機能概要
- 使用方法
- パラメータ説明
- 戻り値
- 使用例
- 注意事項
    `;

    return await this.suggestCode(prompt, { model });
  }

  async createWorkflow(taskDescription, options = {}) {
    const model = options.model || this.defaultModel;

    const prompt = `
以下のタスクを実行するGitHub Actionsワークフローを作成してください:
"${taskDescription}"

要件:
- セキュリティベストプラクティスに準拠
- 適切なエラーハンドリング
- 再実行可能な設計
- 詳細なログ出力
    `;

    return await this.suggestCode(prompt, { model });
  }
}

// 高度なワークフロー自動化クラス
class AutomatedWorkflow {
  constructor(copilotIntegration, claudeAgent) {
    this.copilot = copilotIntegration;
    this.claude = claudeAgent;
  }

  async fullCodeReviewWorkflow(prNumber) {
    console.log(`🔍 PR #${prNumber} の包括的レビューを開始...`);

    try {
      // 1. Copilot によるコードレビュー
      const copilotReview = await this.copilot.reviewPullRequest(prNumber);

      // 2. Claude による深い分析
      const claudeAnalysis = await this.claude.processTask(
        `PR #${prNumber} のコードレビュー結果を分析し、追加の改善提案を行ってください`,
        { copilotReview }
      );

      // 3. 統合レポート生成
      const report = {
        prNumber,
        timestamp: new Date().toISOString(),
        copilotReview: copilotReview,
        claudeAnalysis: claudeAnalysis,
        summary: await this.generateReviewSummary(copilotReview, claudeAnalysis)
      };

      return report;

    } catch (error) {
      console.error('ワークフローエラー:', error);
      throw error;
    }
  }

  async generateReviewSummary(copilotReview, claudeAnalysis) {
    const prompt = `
以下のレビュー結果を統合して、簡潔なサマリーを作成してください:

Copilot レビュー:
${JSON.stringify(copilotReview, null, 2)}

Claude 分析:
${JSON.stringify(claudeAnalysis, null, 2)}

サマリーには以下を含めてください:
- 主要な問題点
- 推奨する修正アクション
- 優先度評価
    `;

    return await this.claude.processTask(prompt);
  }
}

// 使用例
async function workflowExample() {
  const copilot = new CopilotIntegration();
  const claude = new Claude4Agent();
  const workflow = new AutomatedWorkflow(copilot, claude);

  // 自動レビューワークフロー実行
  const report = await workflow.fullCodeReviewWorkflow(123);
  console.log('レビューレポート:', report);
}

module.exports = { 
  CopilotIntegration, 
  AutomatedWorkflow 
};

Section 3: プロダクション運用ガイド

セキュリティ設定

# .github/workflows/security-checks.yml
name: AI-Enhanced Security Pipeline

on:
  push:
    branches: [main, develop]
  pull_request:
    branches: [main]
  schedule:
    - cron: '0 2 * * 1' # 毎週月曜日 2:00 AM

jobs:
  ai-security-audit:
    runs-on: ubuntu-latest
    permissions:
      contents: read
      security-events: write

    steps:
      - uses: actions/checkout@v4

      - name: Setup Security Environment
        run: |
          # セキュリティツールのセットアップ
          npm install -g @anthropic-ai/claude-code
          pip install bandit safety

      - name: Claude Security Analysis
        run: |
          # Claude による包括的セキュリティ分析
          claude -c security-scan --output security-analysis.json
        env:
          ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}

      - name: Dependency Security Check
        run: |
          # 依存関係の脆弱性チェック
          npm audit --audit-level high --json > npm-audit.json
          safety check --json > python-safety.json

      - name: Static Analysis Integration
        run: |
          # 静的解析結果をClaude で分析
          claude "セキュリティスキャン結果を分析し、優先度付きの修正計画を作成してください" \
            --context security-analysis.json \
            --context npm-audit.json \
            --output security-report.md

      - name: Upload Security Report
        uses: github/codeql-action/upload-sarif@v3
        with:
          sarif_file: security-report.sarif

      - name: Comment Security Summary
        uses: actions/github-script@v7
        if: github.event_name == 'pull_request'
        with:
          script: |
            const fs = require('fs');
            const report = fs.readFileSync('security-report.md', 'utf8');

            await github.rest.issues.createComment({
              issue_number: context.issue.number,
              owner: context.repo.owner,
              repo: context.repo.repo,
              body: `## 🔒 AI-Enhanced Security Analysis\n\n${report}`
            });

モニタリング設定

// src/monitoring/ai-metrics.js - AI使用状況の監視

const { EventEmitter } = require('events');

class AIMetricsCollector extends EventEmitter {
  constructor(options = {}) {
    super();
    this.metrics = {
      requests: 0,
      totalTokens: 0,
      modelUsage: {},
      errors: 0,
      responseTime: []
    };

    this.startTime = Date.now();
    this.reportInterval = options.reportInterval || 300000; // 5分

    this.startReporting();
  }

  recordRequest(model, tokens, responseTime, success = true) {
    this.metrics.requests++;
    this.metrics.totalTokens += tokens;

    if (!this.metrics.modelUsage[model]) {
      this.metrics.modelUsage[model] = { requests: 0, tokens: 0 };
    }
    this.metrics.modelUsage[model].requests++;
    this.metrics.modelUsage[model].tokens += tokens;

    if (!success) {
      this.metrics.errors++;
    }

    this.metrics.responseTime.push(responseTime);

    this.emit('request_recorded', {
      model,
      tokens,
      responseTime,
      success
    });
  }

  getMetrics() {
    const uptime = Date.now() - this.startTime;
    const avgResponseTime = this.metrics.responseTime.length > 0 
      ? this.metrics.responseTime.reduce((a, b) => a + b, 0) / this.metrics.responseTime.length
      : 0;

    return {
      ...this.metrics,
      uptime,
      avgResponseTime,
      requestsPerMinute: (this.metrics.requests / (uptime / 60000)).toFixed(2),
      errorRate: ((this.metrics.errors / this.metrics.requests) * 100).toFixed(2)
    };
  }

  startReporting() {
    setInterval(() => {
      const metrics = this.getMetrics();
      this.emit('metrics_report', metrics);

      // 外部監視システムに送信
      this.sendToMonitoring(metrics);
    }, this.reportInterval);
  }

  async sendToMonitoring(metrics) {
    try {
      // Datadog, New Relic, CloudWatch などに送信
      const payload = {
        timestamp: Date.now(),
        service: 'ai-agent-service',
        metrics: metrics
      };

      // 実際の送信処理をここに実装
      console.log('Metrics sent:', payload);

    } catch (error) {
      console.error('Monitoring send error:', error);
    }
  }
}

// メトリクス統合クラス
class AIPerformanceMonitor {
  constructor() {
    this.collector = new AIMetricsCollector();
    this.alerts = new Map();

    this.collector.on('metrics_report', (metrics) => {
      this.checkAlerts(metrics);
    });
  }

  checkAlerts(metrics) {
    // エラー率アラート
    if (parseFloat(metrics.errorRate) > 5) {
      this.triggerAlert('high_error_rate', {
        rate: metrics.errorRate,
        threshold: 5
      });
    }

    // レスポンス時間アラート
    if (metrics.avgResponseTime > 10000) {
      this.triggerAlert('slow_response', {
        avgTime: metrics.avgResponseTime,
        threshold: 10000
      });
    }

    // トークン使用量アラート(コスト管理)
    if (metrics.totalTokens > 1000000) {
      this.triggerAlert('high_token_usage', {
        tokens: metrics.totalTokens,
        threshold: 1000000
      });
    }
  }

  triggerAlert(type, data) {
    const alertKey = `${type}_${Date.now()}`;

    if (!this.alerts.has(type) || Date.now() - this.alerts.get(type) > 900000) {
      this.alerts.set(type, Date.now());

      console.error(`🚨 Alert: ${type}`, data);

      // Slack、Email、Discord などに通知
      this.sendAlert(type, data);
    }
  }

  async sendAlert(type, data) {
    // 実際のアラート送信処理
    const webhook = process.env.SLACK_WEBHOOK_URL;
    if (webhook) {
      try {
        const response = await fetch(webhook, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            text: `🚨 AI System Alert: ${type}`,
            attachments: [{
              color: 'danger',
              fields: Object.entries(data).map(([key, value]) => ({
                title: key,
                value: value.toString(),
                short: true
              }))
            }]
          })
        });

        if (!response.ok) {
          throw new Error(`HTTP ${response.status}`);
        }
      } catch (error) {
        console.error('Alert send failed:', error);
      }
    }
  }
}

module.exports = { AIMetricsCollector, AIPerformanceMonitor };

まとめ

  • 完全自動化環境: スクリプト一つで本格的なAI開発環境を構築
  • 実用的コード例: 実際のプロジェクトで使える具体的な実装
  • プロダクション対応: セキュリティとモニタリングを含む運用レベルの設定
  • 継続的改善: GitHub Actionsによる自動化でAIが常にコード品質を監視

この実装ガイドにより、Claude 4とGitHub Copilotを活用した実際の開発プロジェクトを即座に開始できます。各コード例は実際に動作し、プロダクション環境でも使用可能な品質で作成されています。

関連記事