Claude 4・OpenAI Codex・Gemini CLI実装ガイド:開発者向け実践的導入手順 2025¶
はじめに¶
AI開発者必見:Claude 4登場、OpenAI Codexとターミナル革命 - 2025年7月22日速報(アーカイブ)で紹介した最新AI開発ツールの実際の導入方法と実装例を詳しく解説します。理論から実践へ移る開発者のための具体的なガイドです。
この記事のポイント¶
環境構築の自動化
3つのAIツールを統合した最適な開発環境を30分で構築
コード生成の最適化
各ツールの特性を活かした効率的なコード生成ワークフロー
セキュアな統合
企業環境でも安全に使用できるAPI設定とデータ保護手順
パフォーマンス測定
生産性向上の定量的評価とボトルネック特定手法
Claude 4実装:長期タスク対応環境の構築¶
環境セットアップ¶
# Claude 4用の開発環境構築
mkdir claude4-workspace && cd claude4-workspace
# 必要な依存関係をインストール
pip install anthropic python-dotenv pyyaml
# 設定ファイルの準備
cat > claude4_config.yaml << 'EOF'
# Claude 4設定ファイル
claude_config:
model: "claude-4-opus-20250514"
max_tokens: 8192
temperature: 0.1
project_settings:
context_window: 200000
long_task_mode: true
multi_file_analysis: true
security:
api_key_env: "CLAUDE_API_KEY"
log_level: "INFO"
sensitive_data_filter: true
EOF
Claude 4クライアント実装¶
# claude4_client.py
import os
import yaml
from anthropic import Anthropic
from typing import List, Dict, Any
import logging
class Claude4Client:
def __init__(self, config_path: str = "claude4_config.yaml"):
"""Claude 4クライアントの初期化"""
with open(config_path, 'r') as f:
self.config = yaml.safe_load(f)
self.client = Anthropic(
api_key=os.getenv(self.config['security']['api_key_env'])
)
# ログ設定
logging.basicConfig(
level=getattr(logging, self.config['security']['log_level'])
)
self.logger = logging.getLogger(__name__)
def analyze_codebase(self, file_paths: List[str]) -> Dict[str, Any]:
"""複数ファイルの包括的解析"""
combined_content = ""
file_map = {}
for path in file_paths:
try:
with open(path, 'r', encoding='utf-8') as f:
content = f.read()
file_map[path] = len(combined_content)
combined_content += f"\n\n--- {path} ---\n{content}"
except Exception as e:
self.logger.error(f"ファイル読み込みエラー: {path} - {e}")
message = self.client.messages.create(
model=self.config['claude_config']['model'],
max_tokens=self.config['claude_config']['max_tokens'],
temperature=self.config['claude_config']['temperature'],
messages=[
{
"role": "user",
"content": f"""
以下のコードベースを解析して、以下の情報を提供してください:
1. アーキテクチャの概要
2. 潜在的な問題点
3. 改善提案
4. 依存関係の分析
コードベース:
{combined_content}
"""
}
]
)
return {
"analysis": message.content[0].text,
"file_count": len(file_paths),
"total_tokens": len(combined_content.split())
}
def long_term_refactoring(self, project_path: str, task_description: str) -> str:
"""長期リファクタリングタスクの実行"""
# プロジェクト構造の分析
import os
import glob
python_files = glob.glob(f"{project_path}/**/*.py", recursive=True)
js_files = glob.glob(f"{project_path}/**/*.js", recursive=True)
analysis = self.analyze_codebase(python_files + js_files)
refactoring_prompt = f"""
長期リファクタリングタスク: {task_description}
現在の分析結果:
{analysis['analysis']}
以下の形式で具体的なリファクタリング計画を作成してください:
1. 段階的な実行手順(各段階は1-2時間以内)
2. 各段階の具体的なコード変更
3. テスト戦略
4. リスク評価と対策
"""
message = self.client.messages.create(
model=self.config['claude_config']['model'],
max_tokens=self.config['claude_config']['max_tokens'],
messages=[{"role": "user", "content": refactoring_prompt}]
)
return message.content[0].text
# 使用例
if __name__ == "__main__":
client = Claude4Client()
# 複数ファイルの解析例
files_to_analyze = ["src/main.py", "src/utils.py", "tests/test_main.py"]
result = client.analyze_codebase(files_to_analyze)
print("分析結果:", result['analysis'])
# 長期リファクタリング計画の生成
plan = client.long_term_refactoring(
"./my_project",
"モノリスをマイクロサービスに分割"
)
print("リファクタリング計画:", plan)
Claude 4活用ポイント
Claude 4の長期タスク実行能力を最大限活用するには、タスクを明確に構造化し、中間結果を定期的に保存することが重要です
OpenAI Codex実装:ChatGPT統合開発環境¶
Codex Agent設定¶
# codex_agent.py
import openai
import json
import subprocess
import os
from typing import Dict, List, Any
class CodexAgent:
def __init__(self, api_key: str):
"""OpenAI Codex Agentの初期化"""
openai.api_key = api_key
self.conversation_history = []
def create_feature(self, feature_description: str, project_context: str) -> Dict[str, Any]:
"""完全なソフトウェア機能の実装"""
system_prompt = f"""
あなたは経験豊富なソフトウェア開発者です。以下のプロジェクトコンテキストで新機能を実装してください。
プロジェクトコンテキスト:
{project_context}
実装要件:
1. 機能仕様の詳細化
2. 必要なファイルとディレクトリ構造
3. 実装コード(完全版)
4. テストコード
5. ドキュメント
"""
response = openai.ChatCompletion.create(
model="gpt-4-code-interpreter", # Codex専用モデル
messages=[
{"role": "system", "content": system_prompt},
{"role": "user", "content": f"実装する機能: {feature_description}"}
],
temperature=0.1,
max_tokens=4000
)
result = response.choices[0].message.content
# 結果の構造化
return self._parse_implementation_result(result)
def fix_bugs(self, error_log: str, source_code: str) -> Dict[str, str]:
"""自動バグ修正"""
bug_fix_prompt = f"""
以下のエラーログとソースコードを分析して、バグを特定し、修正版のコードを提供してください。
エラーログ:
{error_log}
ソースコード:
{source_code}
以下の形式で回答してください:
1. バグの原因
2. 修正版コード
3. 修正の説明
4. 追加テスト提案
"""
response = openai.ChatCompletion.create(
model="gpt-4-code-interpreter",
messages=[{"role": "user", "content": bug_fix_prompt}],
temperature=0.1
)
return self._parse_bug_fix_result(response.choices[0].message.content)
def run_tests(self, test_command: str = "pytest") -> Dict[str, Any]:
"""包括的なテスト自動化"""
try:
# テスト実行
result = subprocess.run(
test_command.split(),
capture_output=True,
text=True,
timeout=300
)
test_output = {
"stdout": result.stdout,
"stderr": result.stderr,
"return_code": result.returncode,
"success": result.returncode == 0
}
# テスト結果をCodexで分析
if not test_output["success"]:
analysis = self._analyze_test_failures(test_output)
test_output["analysis"] = analysis
test_output["suggested_fixes"] = self._suggest_test_fixes(analysis)
return test_output
except subprocess.TimeoutExpired:
return {"error": "テスト実行がタイムアウトしました"}
except Exception as e:
return {"error": f"テスト実行エラー: {str(e)}"}
def _parse_implementation_result(self, result: str) -> Dict[str, Any]:
"""実装結果のパース"""
# 実装結果を構造化(実際の実装では正規表現やNLPを使用)
return {
"specification": "機能仕様...",
"file_structure": ["file1.py", "file2.py"],
"implementation": {"file1.py": "code content..."},
"tests": {"test_file1.py": "test code..."},
"documentation": "README内容..."
}
def _parse_bug_fix_result(self, result: str) -> Dict[str, str]:
"""バグ修正結果のパース"""
return {
"bug_cause": "バグの原因...",
"fixed_code": "修正されたコード...",
"explanation": "修正の説明...",
"additional_tests": "追加テスト..."
}
def _analyze_test_failures(self, test_output: Dict[str, Any]) -> str:
"""テスト失敗の分析"""
analysis_prompt = f"""
以下のテスト実行結果を分析して、失敗の原因を特定してください:
標準出力:
{test_output['stdout']}
エラー出力:
{test_output['stderr']}
"""
response = openai.ChatCompletion.create(
model="gpt-4-code-interpreter",
messages=[{"role": "user", "content": analysis_prompt}],
temperature=0.1
)
return response.choices[0].message.content
def _suggest_test_fixes(self, analysis: str) -> List[str]:
"""テスト修正提案"""
# 分析結果を基に修正提案を生成
return ["修正提案1", "修正提案2", "修正提案3"]
# 使用例とワークフロー統合
def create_development_workflow():
"""開発ワークフローの作成"""
agent = CodexAgent(os.getenv("OPENAI_API_KEY"))
# 1. 新機能の実装
feature_result = agent.create_feature(
"ユーザー認証システム",
"Flask Webアプリケーション、PostgreSQLデータベース使用"
)
# 2. 実装されたコードの保存
for filename, content in feature_result["implementation"].items():
with open(filename, 'w') as f:
f.write(content)
# 3. テストの実行
test_result = agent.run_tests()
# 4. バグがあれば修正
if not test_result["success"]:
for filename in feature_result["implementation"].keys():
with open(filename, 'r') as f:
source_code = f.read()
bug_fix = agent.fix_bugs(test_result["stderr"], source_code)
# 修正版の保存
with open(filename, 'w') as f:
f.write(bug_fix["fixed_code"])
return feature_result, test_result
if __name__ == "__main__":
create_development_workflow()
GitHub Actions統合¶
# .github/workflows/codex-integration.yml
name: OpenAI Codex Integration
on:
push:
branches: [ main, develop ]
pull_request:
branches: [ main ]
env:
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
jobs:
codex-analysis:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Set up Python
uses: actions/setup-python@v4
with:
python-version: '3.11'
- name: Install dependencies
run: |
pip install openai pytest black flake8
- name: Run Codex Code Review
run: |
python scripts/codex_review.py --changed-files ${{ github.event.pull_request.changed_files }}
- name: Auto-fix Code Issues
run: |
python scripts/codex_autofix.py
- name: Run Tests with Codex
run: |
python scripts/codex_test_runner.py
- name: Comment PR with Analysis
uses: actions/github-script@v6
with:
script: |
const fs = require('fs');
const analysis = fs.readFileSync('codex_analysis.md', 'utf8');
github.rest.issues.createComment({
issue_number: context.issue.number,
owner: context.repo.owner,
repo: context.repo.repo,
body: analysis
});
Codex使用時の注意点
OpenAI Codexは研究プレビュー版のため、本番環境での使用前に十分なテストと検証を行ってください
Google Gemini CLI実装:ターミナル統合¶
インストールと初期設定¶
# Gemini CLIのインストール
curl -fsSL https://cli.gemini.google.com/install.sh | bash
# 環境変数の設定
export GEMINI_API_KEY="your_api_key_here"
export GEMINI_PROJECT_ID="your_project_id"
# 設定ファイルの作成
mkdir -p ~/.config/gemini
cat > ~/.config/gemini/config.toml << 'EOF'
[default]
model = "gemini-2.0-flash-exp"
temperature = 0.1
max_tokens = 8192
[coding]
model = "gemini-2.0-flash-thinking-exp-1219"
temperature = 0.0
context_window = 32000
[security]
log_requests = false
sanitize_output = true
respect_gitignore = true
EOF
カスタムコマンドの作成¶
# ~/.local/bin/ai-dev (実行可能にする: chmod +x ~/.local/bin/ai-dev)
#!/bin/bash
# AI開発支援スクリプト
set -e
COMMAND=$1
shift
case $COMMAND in
"review")
echo "🔍 コードレビューを実行中..."
gemini --profile coding "以下のコードをレビューして、改善点と潜在的な問題を指摘してください。特にセキュリティ、パフォーマンス、保守性の観点から分析してください。" --files "$@"
;;
"optimize")
echo "⚡ パフォーマンス最適化の提案を生成中..."
gemini --profile coding "以下のコードのパフォーマンスを分析し、最適化の提案を具体的なコード例と共に提示してください。" --files "$@"
;;
"test")
echo "🧪 テストケース生成中..."
gemini --profile coding "以下のコードに対する包括的なテストケースを生成してください。エッジケース、エラーハンドリング、パフォーマンステストを含めてください。" --files "$@"
;;
"debug")
if [ -f "error.log" ]; then
echo "🐛 デバッグ分析中..."
gemini --profile coding "以下のエラーログとソースコードを分析して、問題の原因と解決策を提案してください。" --files error.log "$@"
else
echo "❌ error.logファイルが見つかりません"
exit 1
fi
;;
"refactor")
echo "🔧 リファクタリング提案を生成中..."
gemini --profile coding "以下のコードをリファクタリングして、読みやすさ、保守性、拡張性を向上させる具体的な改善案を提示してください。" --files "$@"
;;
"explain")
echo "📖 コード解説を生成中..."
gemini --profile coding "以下のコードの動作を詳しく解説してください。アルゴリズム、データ構造、設計パターンの観点から説明してください。" --files "$@"
;;
*)
echo "AI Development Assistant"
echo ""
echo "使用法: ai-dev <command> [files...]"
echo ""
echo "コマンド:"
echo " review - コードレビューの実行"
echo " optimize - パフォーマンス最適化提案"
echo " test - テストケース生成"
echo " debug - エラー分析(error.log必須)"
echo " refactor - リファクタリング提案"
echo " explain - コード解説"
echo ""
echo "例:"
echo " ai-dev review src/main.py"
echo " ai-dev test src/utils.py"
echo " ai-dev debug src/problematic.py"
;;
esac
高度なワークフロー統合¶
# gemini_workflow.py
import subprocess
import json
import os
from typing import Dict, List, Any
class GeminiWorkflow:
def __init__(self, config_path: str = "~/.config/gemini/config.toml"):
self.config_path = config_path
def batch_code_analysis(self, project_path: str) -> Dict[str, Any]:
"""プロジェクト全体の一括分析"""
# Pythonファイルの収集
python_files = self._collect_files(project_path, "*.py")
# JavaScript/TypeScriptファイルの収集
js_files = self._collect_files(project_path, "*.js") + \
self._collect_files(project_path, "*.ts")
results = {
"python_analysis": self._analyze_files(python_files, "python"),
"javascript_analysis": self._analyze_files(js_files, "javascript"),
"architecture_analysis": self._analyze_architecture(project_path),
"security_analysis": self._security_scan(project_path)
}
return results
def _collect_files(self, project_path: str, pattern: str) -> List[str]:
"""ファイルパターンに基づいてファイルを収集"""
result = subprocess.run(
f"find {project_path} -name '{pattern}' -type f",
shell=True,
capture_output=True,
text=True
)
return result.stdout.strip().split('\n') if result.stdout.strip() else []
def _analyze_files(self, files: List[str], language: str) -> Dict[str, Any]:
"""言語固有の分析"""
if not files:
return {"status": "no_files", "language": language}
# 最大5ファイルまでに制限(APIレート制限対策)
files_to_analyze = files[:5]
analysis_results = {}
for file_path in files_to_analyze:
try:
result = subprocess.run(
f"gemini --profile coding 'このコードの品質を評価し、改善点を提案してください' --files {file_path}",
shell=True,
capture_output=True,
text=True,
timeout=60
)
analysis_results[file_path] = {
"status": "success",
"analysis": result.stdout,
"issues": self._extract_issues(result.stdout)
}
except subprocess.TimeoutExpired:
analysis_results[file_path] = {
"status": "timeout",
"error": "Analysis timed out"
}
except Exception as e:
analysis_results[file_path] = {
"status": "error",
"error": str(e)
}
return {
"language": language,
"files_analyzed": len(analysis_results),
"results": analysis_results
}
def _analyze_architecture(self, project_path: str) -> Dict[str, Any]:
"""アーキテクチャ分析"""
try:
# プロジェクト構造の取得
structure_result = subprocess.run(
f"tree {project_path} -I '__pycache__|node_modules|.git'",
shell=True,
capture_output=True,
text=True
)
# Geminiによるアーキテクチャ分析
gemini_result = subprocess.run(
f"echo '{structure_result.stdout}' | gemini --profile coding 'このプロジェクト構造を分析して、アーキテクチャの特徴、設計パターン、改善提案を述べてください'",
shell=True,
capture_output=True,
text=True
)
return {
"status": "success",
"project_structure": structure_result.stdout,
"architecture_analysis": gemini_result.stdout
}
except Exception as e:
return {
"status": "error",
"error": str(e)
}
def _security_scan(self, project_path: str) -> Dict[str, Any]:
"""セキュリティスキャン"""
security_patterns = [
"password.*=",
"api[_-]?key.*=",
"secret.*=",
"token.*=",
"eval\\(",
"exec\\(",
"subprocess\\.call"
]
findings = []
for pattern in security_patterns:
try:
result = subprocess.run(
f"grep -r -n '{pattern}' {project_path} --include='*.py' --include='*.js' --include='*.ts'",
shell=True,
capture_output=True,
text=True
)
if result.stdout:
findings.append({
"pattern": pattern,
"matches": result.stdout.strip().split('\n')
})
except Exception as e:
continue
return {
"status": "completed",
"findings_count": len(findings),
"findings": findings,
"risk_level": "high" if len(findings) > 5 else "medium" if len(findings) > 0 else "low"
}
def _extract_issues(self, analysis_text: str) -> List[str]:
"""分析結果から問題点を抽出"""
# 簡単な実装例(実際はより洗練されたNLP処理が必要)
issues = []
lines = analysis_text.split('\n')
for line in lines:
if any(keyword in line.lower() for keyword in ['問題', 'issue', 'bug', 'error', '改善']):
issues.append(line.strip())
return issues
# 使用例
def main():
workflow = GeminiWorkflow()
# プロジェクト分析の実行
project_path = "./my_project"
analysis_results = workflow.batch_code_analysis(project_path)
# 結果の保存
with open("analysis_report.json", "w", encoding="utf-8") as f:
json.dump(analysis_results, f, indent=2, ensure_ascii=False)
# サマリーレポートの生成
print("🔍 プロジェクト分析完了")
print(f"Python files analyzed: {analysis_results['python_analysis']['files_analyzed']}")
print(f"JavaScript files analyzed: {analysis_results['javascript_analysis']['files_analyzed']}")
print(f"Security risk level: {analysis_results['security_analysis']['risk_level']}")
if __name__ == "__main__":
main()
Gemini CLI活用のコツ
ターミナルでの効率的な作業のため、エイリアスやカスタムスクリプトを活用して、頻繁に使用するコマンドを短縮化すると効果的です
統合ワークフローの構築¶
3ツール連携スクリプト¶
# integrated_ai_workflow.py
import asyncio
import json
from datetime import datetime
from claude4_client import Claude4Client
from codex_agent import CodexAgent
from gemini_workflow import GeminiWorkflow
class IntegratedAIWorkflow:
def __init__(self):
self.claude = Claude4Client()
self.codex = CodexAgent(os.getenv("OPENAI_API_KEY"))
self.gemini = GeminiWorkflow()
async def comprehensive_project_analysis(self, project_path: str) -> Dict[str, Any]:
"""3つのAIツールを使った包括的プロジェクト分析"""
print("🚀 包括的プロジェクト分析を開始...")
# 並行して各ツールで分析を実行
tasks = [
self._claude_analysis(project_path),
self._codex_analysis(project_path),
self._gemini_analysis(project_path)
]
claude_result, codex_result, gemini_result = await asyncio.gather(*tasks)
# 結果の統合
integrated_result = self._integrate_analyses(
claude_result, codex_result, gemini_result
)
# 最終レポートの生成
final_report = self._generate_final_report(integrated_result)
return {
"timestamp": datetime.now().isoformat(),
"project_path": project_path,
"individual_analyses": {
"claude": claude_result,
"codex": codex_result,
"gemini": gemini_result
},
"integrated_analysis": integrated_result,
"final_report": final_report
}
async def _claude_analysis(self, project_path: str) -> Dict[str, Any]:
"""Claude 4による長期的視点での分析"""
print("🧠 Claude 4で分析中...")
# プロジェクトファイルの収集
import glob
python_files = glob.glob(f"{project_path}/**/*.py", recursive=True)[:10]
if python_files:
analysis = self.claude.analyze_codebase(python_files)
# 長期リファクタリング計画も生成
refactoring_plan = self.claude.long_term_refactoring(
project_path,
"コードベース全体の保守性とスケーラビリティの向上"
)
return {
"tool": "Claude 4",
"strength": "長期的視点とアーキテクチャ分析",
"codebase_analysis": analysis,
"refactoring_plan": refactoring_plan,
"status": "success"
}
else:
return {
"tool": "Claude 4",
"status": "no_python_files",
"message": "分析対象のPythonファイルが見つかりませんでした"
}
async def _codex_analysis(self, project_path: str) -> Dict[str, Any]:
"""OpenAI Codexによる実装重視の分析"""
print("🤖 OpenAI Codexで分析中...")
try:
# テスト実行
test_result = self.codex.run_tests("python -m pytest tests/")
# バグ修正提案(テストが失敗した場合)
bug_fixes = []
if not test_result.get("success", False):
# 簡略化した実装
bug_fixes = ["テスト失敗の修正提案を生成"]
return {
"tool": "OpenAI Codex",
"strength": "実装とテスト自動化",
"test_results": test_result,
"bug_fixes": bug_fixes,
"status": "success"
}
except Exception as e:
return {
"tool": "OpenAI Codex",
"status": "error",
"error": str(e)
}
async def _gemini_analysis(self, project_path: str) -> Dict[str, Any]:
"""Google Gemini CLIによる実用的分析"""
print("💎 Google Gemini CLIで分析中...")
try:
analysis = self.gemini.batch_code_analysis(project_path)
return {
"tool": "Google Gemini CLI",
"strength": "実用的な問題発見とセキュリティ",
"analysis": analysis,
"status": "success"
}
except Exception as e:
return {
"tool": "Google Gemini CLI",
"status": "error",
"error": str(e)
}
def _integrate_analyses(self, claude_result: Dict, codex_result: Dict, gemini_result: Dict) -> Dict[str, Any]:
"""3つの分析結果を統合"""
# 共通の問題点を抽出
common_issues = self._find_common_issues(claude_result, codex_result, gemini_result)
# 優先度付きタスクリストの生成
prioritized_tasks = self._generate_prioritized_tasks(claude_result, codex_result, gemini_result)
# 各ツールの強みを活かした役割分担
tool_recommendations = {
"long_term_planning": "Claude 4の長期リファクタリング計画を採用",
"immediate_fixes": "OpenAI Codexのバグ修正提案を優先実装",
"security_hardening": "Gemini CLIのセキュリティ分析結果を基に対策実施"
}
return {
"common_issues": common_issues,
"prioritized_tasks": prioritized_tasks,
"tool_recommendations": tool_recommendations,
"integration_timestamp": datetime.now().isoformat()
}
def _find_common_issues(self, *results) -> List[str]:
"""複数の分析結果から共通問題を抽出"""
# 簡略化した実装
return [
"パフォーマンス最適化の必要性",
"エラーハンドリングの改善",
"ドキュメントの不足"
]
def _generate_prioritized_tasks(self, *results) -> List[Dict[str, Any]]:
"""優先度付きタスクリストの生成"""
return [
{
"priority": "high",
"task": "セキュリティ脆弱性の修正",
"estimated_time": "2-4時間",
"assigned_tool": "Gemini CLI"
},
{
"priority": "medium",
"task": "テスト失敗の修正",
"estimated_time": "1-2時間",
"assigned_tool": "OpenAI Codex"
},
{
"priority": "low",
"task": "長期アーキテクチャ改善",
"estimated_time": "1-2週間",
"assigned_tool": "Claude 4"
}
]
def _generate_final_report(self, integrated_analysis: Dict[str, Any]) -> str:
"""最終レポートの生成"""
report = f"""
# 包括的AI分析レポート
## 分析サマリー
- 共通問題数: {len(integrated_analysis['common_issues'])}
- 優先タスク数: {len(integrated_analysis['prioritized_tasks'])}
- 生成日時: {integrated_analysis['integration_timestamp']}
## 重要な発見事項
{chr(10).join([f"- {issue}" for issue in integrated_analysis['common_issues']])}
## 推奨アクション
{chr(10).join([f"- {task['task']} (優先度: {task['priority']}, 予想時間: {task['estimated_time']})" for task in integrated_analysis['prioritized_tasks']])}
## 各ツールの推奨用途
- **長期計画**: {integrated_analysis['tool_recommendations']['long_term_planning']}
- **即座の修正**: {integrated_analysis['tool_recommendations']['immediate_fixes']}
- **セキュリティ**: {integrated_analysis['tool_recommendations']['security_hardening']}
"""
return report.strip()
# メイン実行関数
async def main():
workflow = IntegratedAIWorkflow()
project_path = "./my_project" # 分析対象プロジェクト
try:
result = await workflow.comprehensive_project_analysis(project_path)
# 結果の保存
with open("comprehensive_analysis_report.json", "w", encoding="utf-8") as f:
json.dump(result, f, indent=2, ensure_ascii=False)
print("📋 最終レポート:")
print(result["final_report"])
print(f"\n✅ 詳細な分析結果は comprehensive_analysis_report.json に保存されました")
except Exception as e:
print(f"❌ 分析中にエラーが発生しました: {e}")
if __name__ == "__main__":
asyncio.run(main())
パフォーマンス測定と最適化¶
生産性測定ツール¶
# productivity_metrics.py
import time
import json
import subprocess
from datetime import datetime, timedelta
from typing import Dict, List, Any
class ProductivityMetrics:
def __init__(self):
self.metrics_file = "ai_productivity_metrics.json"
self.load_existing_metrics()
def load_existing_metrics(self):
"""既存の測定結果を読み込み"""
try:
with open(self.metrics_file, 'r') as f:
self.metrics = json.load(f)
except FileNotFoundError:
self.metrics = {
"sessions": [],
"summary": {
"total_sessions": 0,
"average_session_time": 0,
"total_lines_generated": 0,
"total_bugs_fixed": 0
}
}
def start_session(self, task_description: str, ai_tools_used: List[str]) -> str:
"""開発セッションの開始"""
session_id = f"session_{int(time.time())}"
session_data = {
"session_id": session_id,
"task_description": task_description,
"ai_tools_used": ai_tools_used,
"start_time": datetime.now().isoformat(),
"end_time": None,
"duration_minutes": 0,
"lines_generated": 0,
"files_modified": [],
"bugs_fixed": 0,
"tests_written": 0,
"status": "in_progress"
}
self.current_session = session_data
print(f"📊 セッション開始: {session_id}")
print(f"タスク: {task_description}")
print(f"使用ツール: {', '.join(ai_tools_used)}")
return session_id
def end_session(self, session_id: str, final_status: str = "completed") -> Dict[str, Any]:
"""開発セッションの終了"""
if not hasattr(self, 'current_session'):
raise ValueError("アクティブなセッションが見つかりません")
# セッション終了時間の記録
end_time = datetime.now()
start_time = datetime.fromisoformat(self.current_session["start_time"])
duration = end_time - start_time
self.current_session.update({
"end_time": end_time.isoformat(),
"duration_minutes": int(duration.total_seconds() / 60),
"status": final_status
})
# コード変更の分析
self._analyze_code_changes()
# セッションデータの保存
self.metrics["sessions"].append(self.current_session)
self._update_summary()
self._save_metrics()
# 結果の表示
self._display_session_results()
return self.current_session
def _analyze_code_changes(self):
"""コード変更の分析"""
try:
# Gitを使用して変更を分析
git_diff = subprocess.run(
["git", "diff", "--numstat", "HEAD"],
capture_output=True,
text=True
)
if git_diff.stdout:
lines = git_diff.stdout.strip().split('\n')
total_additions = 0
files_modified = []
for line in lines:
parts = line.split('\t')
if len(parts) >= 3:
additions = int(parts[0]) if parts[0] != '-' else 0
filename = parts[2]
total_additions += additions
files_modified.append(filename)
self.current_session["lines_generated"] = total_additions
self.current_session["files_modified"] = files_modified
# テストファイルの検出
test_files = [f for f in self.current_session["files_modified"]
if "test" in f.lower() or f.endswith("_test.py")]
self.current_session["tests_written"] = len(test_files)
except Exception as e:
print(f"⚠️ コード変更の分析中にエラー: {e}")
def _update_summary(self):
"""サマリー情報の更新"""
sessions = self.metrics["sessions"]
if sessions:
total_sessions = len(sessions)
total_time = sum(s["duration_minutes"] for s in sessions)
total_lines = sum(s["lines_generated"] for s in sessions)
total_bugs = sum(s["bugs_fixed"] for s in sessions)
self.metrics["summary"].update({
"total_sessions": total_sessions,
"average_session_time": total_time / total_sessions if total_sessions > 0 else 0,
"total_lines_generated": total_lines,
"total_bugs_fixed": total_bugs,
"last_updated": datetime.now().isoformat()
})
def _save_metrics(self):
"""メトリクスファイルの保存"""
with open(self.metrics_file, 'w') as f:
json.dump(self.metrics, f, indent=2, ensure_ascii=False)
def _display_session_results(self):
"""セッション結果の表示"""
session = self.current_session
print("\n📈 セッション結果:")
print(f" 時間: {session['duration_minutes']}分")
print(f" 生成行数: {session['lines_generated']}行")
print(f" 変更ファイル数: {len(session['files_modified'])}")
print(f" 作成テスト数: {session['tests_written']}")
print(f" 修正バグ数: {session['bugs_fixed']}")
# 効率性の評価
if session['duration_minutes'] > 0:
lines_per_minute = session['lines_generated'] / session['duration_minutes']
print(f" 生産性: {lines_per_minute:.1f}行/分")
def generate_productivity_report(self, days: int = 7) -> str:
"""生産性レポートの生成"""
cutoff_date = datetime.now() - timedelta(days=days)
recent_sessions = [
s for s in self.metrics["sessions"]
if datetime.fromisoformat(s["start_time"]) > cutoff_date
]
if not recent_sessions:
return f"過去{days}日間のセッションデータがありません"
# 統計計算
total_time = sum(s["duration_minutes"] for s in recent_sessions)
total_lines = sum(s["lines_generated"] for s in recent_sessions)
avg_session_time = total_time / len(recent_sessions)
# ツール別分析
tool_usage = {}
for session in recent_sessions:
for tool in session["ai_tools_used"]:
tool_usage[tool] = tool_usage.get(tool, 0) + 1
# レポート生成
report = f"""
# AI開発生産性レポート(過去{days}日間)
## 概要
- セッション数: {len(recent_sessions)}
- 総開発時間: {total_time}分 ({total_time/60:.1f}時間)
- 総生成行数: {total_lines}行
- 平均セッション時間: {avg_session_time:.1f}分
## 生産性指標
- 時間あたり生成行数: {total_lines / (total_time/60):.1f}行/時間
- セッションあたり生成行数: {total_lines / len(recent_sessions):.1f}行/セッション
## AI ツール使用状況
{chr(10).join([f"- {tool}: {count}回使用" for tool, count in sorted(tool_usage.items(), key=lambda x: x[1], reverse=True)])}
## 最も生産的なセッション
{self._get_top_sessions(recent_sessions, 3)}
"""
return report.strip()
def _get_top_sessions(self, sessions: List[Dict], top_n: int = 3) -> str:
"""最も生産的なセッションの特定"""
sorted_sessions = sorted(
sessions,
key=lambda s: s["lines_generated"] / max(s["duration_minutes"], 1),
reverse=True
)
result = []
for i, session in enumerate(sorted_sessions[:top_n]):
efficiency = session["lines_generated"] / max(session["duration_minutes"], 1)
result.append(
f"{i+1}. {session['task_description'][:50]}... "
f"({efficiency:.1f}行/分, {session['duration_minutes']}分)"
)
return '\n'.join(result)
# 使用例
def productivity_tracking_example():
"""生産性追跡の使用例"""
tracker = ProductivityMetrics()
# セッション開始
session_id = tracker.start_session(
"新しいAPI機能の実装",
["Claude 4", "OpenAI Codex"]
)
# 開発作業をシミュレート
print("💻 開発作業中...")
time.sleep(2) # 実際の開発時間をシミュレート
# セッション終了
result = tracker.end_session(session_id, "completed")
# レポート生成
report = tracker.generate_productivity_report(7)
print("\n" + report)
return result
if __name__ == "__main__":
productivity_tracking_example()
まとめ¶
- Claude 4: 長期タスクと包括的分析に最適、複雑なリファクタリング計画の立案
- OpenAI Codex: 日常開発支援とテスト自動化、ChatGPT統合による使いやすさ
- Google Gemini CLI: ターミナル直結によるリアルタイム支援、セキュリティスキャン
関連記事¶
- AI開発者必見:Claude 4登場、OpenAI Codexとターミナル革命 - 2025年7月22日速報(アーカイブ)
- Claude Code MCP実践ガイド:開発者向け完全統合手順