Skip to content

AI API

AI APIは、Trae IDEの人工知能機能への包括的なアクセスを提供し、拡張機能がAI駆動の機能を統合できるようにします。

概要

AI APIでは以下のことができます:

  • コード生成とリファクタリング
  • 自然言語でのコード説明
  • インテリジェントなコード補完
  • エラー分析と修正提案
  • ドキュメント生成
  • コードレビューと品質分析
  • 言語間のコード変換
  • カスタムAIワークフローの作成

基本的な使用方法

AIサービスの初期化

typescript
import { TraeAPI } from '@trae/api';

// AIサービスを初期化
const aiService = TraeAPI.ai;

// 利用可能なモデルを確認
const models = await aiService.getAvailableModels();
console.log('利用可能なモデル:', models);

// デフォルトモデルを設定
await aiService.setDefaultModel('gpt-4');

コード生成

typescript
// シンプルなコード生成
const generatedCode = await aiService.generateCode({
  prompt: 'TypeScriptでHTTPサーバーを作成する関数',
  language: 'typescript',
  style: 'modern'
});

console.log('生成されたコード:', generatedCode.code);
console.log('説明:', generatedCode.explanation);

// 現在のエディターに挿入
const editor = TraeAPI.window.activeTextEditor;
if (editor) {
  await editor.edit(editBuilder => {
    editBuilder.insert(editor.selection.active, generatedCode.code);
  });
}

コード説明

typescript
// 選択されたコードを説明
const editor = TraeAPI.window.activeTextEditor;
if (editor && !editor.selection.isEmpty) {
  const selectedCode = editor.document.getText(editor.selection);
  
  const explanation = await aiService.explainCode({
    code: selectedCode,
    language: editor.document.languageId,
    context: 'function-analysis'
  });
  
  console.log('コードの説明:', explanation.description);
  console.log('主要なポイント:', explanation.keyPoints);
  console.log('改善提案:', explanation.suggestions);
}

高度な機能

インテリジェントなリファクタリング

typescript
// コードのリファクタリング提案
const refactoringResult = await aiService.refactorCode({
  code: selectedCode,
  language: 'typescript',
  goals: ['performance', 'readability', 'maintainability'],
  preserveInterface: true
});

console.log('リファクタリング後のコード:', refactoringResult.refactoredCode);
console.log('変更の説明:', refactoringResult.changes);
console.log('パフォーマンス向上:', refactoringResult.improvements);

// 変更を適用
if (refactoringResult.confidence > 0.8) {
  await editor.edit(editBuilder => {
    editBuilder.replace(editor.selection, refactoringResult.refactoredCode);
  });
}

エラー分析と修正

typescript
// エラーの分析と修正提案
const errorAnalysis = await aiService.analyzeError({
  errorMessage: 'TypeError: Cannot read property "length" of undefined',
  code: problematicCode,
  language: 'javascript',
  stackTrace: stackTrace,
  context: {
    fileName: 'user-service.js',
    lineNumber: 42,
    surroundingCode: contextCode
  }
});

console.log('エラーの原因:', errorAnalysis.cause);
console.log('修正提案:', errorAnalysis.fixes);
console.log('予防策:', errorAnalysis.prevention);

// 自動修正を適用
if (errorAnalysis.autoFixAvailable) {
  const fixedCode = await aiService.applyFix({
    code: problematicCode,
    fix: errorAnalysis.recommendedFix
  });
  
  // エディターに適用
  await editor.edit(editBuilder => {
    editBuilder.replace(errorRange, fixedCode.code);
  });
}

ドキュメント生成

typescript
// 関数やクラスのドキュメントを生成
const documentation = await aiService.generateDocumentation({
  code: functionCode,
  language: 'typescript',
  format: 'jsdoc',
  includeExamples: true,
  includeTypes: true
});

console.log('生成されたドキュメント:', documentation.content);

// ドキュメントを挿入
const position = editor.selection.start;
await editor.edit(editBuilder => {
  editBuilder.insert(position, documentation.content + '\n');
});

コードレビュー

typescript
// 包括的なコードレビュー
const review = await aiService.reviewCode({
  code: fileContent,
  language: 'typescript',
  criteria: {
    codeQuality: true,
    performance: true,
    security: true,
    bestPractices: true,
    maintainability: true
  }
});

console.log('総合評価:', review.overallScore);
console.log('問題点:', review.issues);
console.log('改善提案:', review.suggestions);
console.log('良い点:', review.positives);

// レビュー結果をパネルに表示
const reviewPanel = TraeAPI.window.createWebviewPanel(
  'code-review',
  'コードレビュー結果',
  TraeAPI.ViewColumn.Beside,
  { enableScripts: true }
);

reviewPanel.webview.html = generateReviewHTML(review);

専門的なAI機能

言語変換

typescript
// コードを別の言語に変換
const conversion = await aiService.convertLanguage({
  sourceCode: pythonCode,
  sourceLanguage: 'python',
  targetLanguage: 'typescript',
  preserveLogic: true,
  addTypeAnnotations: true
});

console.log('変換されたコード:', conversion.convertedCode);
console.log('変換ノート:', conversion.conversionNotes);
console.log('手動調整が必要な箇所:', conversion.manualAdjustments);

テスト生成

typescript
// ユニットテストを生成
const tests = await aiService.generateTests({
  code: functionCode,
  language: 'typescript',
  testFramework: 'jest',
  coverage: 'comprehensive',
  includeEdgeCases: true
});

console.log('生成されたテスト:', tests.testCode);
console.log('テストケース数:', tests.testCases.length);
console.log('カバレッジ予測:', tests.estimatedCoverage);

// テストファイルを作成
const testFileName = originalFileName.replace('.ts', '.test.ts');
await TraeAPI.workspace.fs.writeFile(
  TraeAPI.Uri.file(testFileName),
  Buffer.from(tests.testCode, 'utf8')
);

パフォーマンス最適化

typescript
// パフォーマンス最適化の提案
const optimization = await aiService.optimizePerformance({
  code: performanceCriticalCode,
  language: 'typescript',
  target: 'web', // 'web', 'node', 'mobile'
  metrics: ['speed', 'memory', 'bundle-size']
});

console.log('最適化されたコード:', optimization.optimizedCode);
console.log('パフォーマンス向上:', optimization.improvements);
console.log('トレードオフ:', optimization.tradeoffs);
console.log('ベンチマーク予測:', optimization.benchmarkPrediction);

セキュリティ分析

typescript
// セキュリティ脆弱性の分析
const securityAnalysis = await aiService.analyzeSecurityVulnerabilities({
  code: applicationCode,
  language: 'typescript',
  framework: 'express',
  checkTypes: ['injection', 'xss', 'csrf', 'authentication', 'authorization']
});

console.log('発見された脆弱性:', securityAnalysis.vulnerabilities);
console.log('セキュリティスコア:', securityAnalysis.securityScore);
console.log('修正提案:', securityAnalysis.fixes);
console.log('セキュリティベストプラクティス:', securityAnalysis.recommendations);

カスタムAIワークフロー

ワークフローの作成

typescript
// カスタムAIワークフローを定義
const customWorkflow = aiService.createWorkflow({
  name: 'full-stack-component-generator',
  steps: [
    {
      name: 'generate-interface',
      type: 'code-generation',
      prompt: 'TypeScriptインターフェースを生成',
      outputVariable: 'interface'
    },
    {
      name: 'generate-component',
      type: 'code-generation',
      prompt: 'Reactコンポーネントを生成',
      inputs: ['interface'],
      outputVariable: 'component'
    },
    {
      name: 'generate-tests',
      type: 'test-generation',
      inputs: ['component'],
      outputVariable: 'tests'
    },
    {
      name: 'generate-docs',
      type: 'documentation',
      inputs: ['interface', 'component'],
      outputVariable: 'documentation'
    }
  ]
});

// ワークフローを実行
const workflowResult = await customWorkflow.execute({
  componentName: 'UserProfile',
  props: ['name', 'email', 'avatar'],
  features: ['editing', 'validation']
});

console.log('生成された成果物:', workflowResult.outputs);

AIアシスタントの作成

typescript
// 専門的なAIアシスタントを作成
const codeReviewAssistant = aiService.createAssistant({
  name: 'CodeReviewBot',
  specialization: 'code-review',
  personality: 'constructive-critic',
  knowledge: {
    languages: ['typescript', 'javascript', 'python'],
    frameworks: ['react', 'express', 'fastapi'],
    standards: ['clean-code', 'solid-principles', 'security-best-practices']
  },
  customPrompts: {
    greeting: 'こんにちは!コードレビューのお手伝いをします。',
    reviewStart: 'コードを詳しく分析しています...',
    reviewComplete: 'レビューが完了しました。以下が分析結果です:'
  }
});

// アシスタントを使用
const assistantReview = await codeReviewAssistant.reviewCode({
  code: codeToReview,
  focusAreas: ['performance', 'security', 'maintainability']
});

AI設定とカスタマイズ

モデル設定

typescript
// 異なるタスクに異なるモデルを設定
await aiService.configureModels({
  codeGeneration: {
    model: 'gpt-4-turbo',
    temperature: 0.3,
    maxTokens: 2048
  },
  codeExplanation: {
    model: 'gpt-4',
    temperature: 0.5,
    maxTokens: 1024
  },
  codeReview: {
    model: 'gpt-4',
    temperature: 0.2,
    maxTokens: 1500
  },
  documentation: {
    model: 'gpt-3.5-turbo',
    temperature: 0.4,
    maxTokens: 800
  }
});

カスタムプロンプト

typescript
// カスタムプロンプトテンプレートを作成
const customPrompts = {
  codeGeneration: `
あなたは経験豊富な{{language}}開発者です。
以下の要件に基づいてコードを生成してください:

要件: {{requirements}}
スタイル: {{codeStyle}}
フレームワーク: {{framework}}

生成するコードは以下の条件を満たしてください:
- 読みやすく保守しやすい
- パフォーマンスが最適化されている
- セキュリティベストプラクティスに従っている
- 適切なエラーハンドリングを含む
- 必要に応じてコメントを含む

コード:
  `,
  
  codeReview: `
以下の{{language}}コードをレビューしてください:

{{code}}

以下の観点から分析してください:
1. コードの品質と可読性
2. パフォーマンスの問題
3. セキュリティの脆弱性
4. ベストプラクティスの遵守
5. 改善提案

建設的で具体的なフィードバックを提供してください。
  `
};

await aiService.setCustomPrompts(customPrompts);

コンテキスト管理

typescript
// プロジェクト固有のコンテキストを設定
const projectContext = {
  projectType: 'web-application',
  technologies: ['typescript', 'react', 'express', 'postgresql'],
  architecture: 'microservices',
  codingStandards: {
    naming: 'camelCase',
    indentation: 2,
    quotes: 'single',
    semicolons: true
  },
  dependencies: await getProjectDependencies(),
  fileStructure: await getProjectStructure()
};

await aiService.setProjectContext(projectContext);

統合とワークフロー

エディター統合

typescript
// エディターコマンドとAI機能を統合
TraeAPI.commands.registerCommand('ai.explainSelection', async () => {
  const editor = TraeAPI.window.activeTextEditor;
  if (!editor || editor.selection.isEmpty) {
    TraeAPI.window.showWarningMessage('コードを選択してください');
    return;
  }

  const selectedCode = editor.document.getText(editor.selection);
  const explanation = await aiService.explainCode({
    code: selectedCode,
    language: editor.document.languageId
  });

  // 説明をホバーで表示
  TraeAPI.window.showInformationMessage(explanation.description);
});

TraeAPI.commands.registerCommand('ai.generateTests', async () => {
  const editor = TraeAPI.window.activeTextEditor;
  if (!editor) return;

  const code = editor.document.getText();
  const tests = await aiService.generateTests({
    code,
    language: editor.document.languageId,
    testFramework: 'jest'
  });

  // 新しいテストファイルを作成
  const testUri = TraeAPI.Uri.file(
    editor.document.fileName.replace(/\.(ts|js)$/, '.test.$1')
  );
  
  await TraeAPI.workspace.fs.writeFile(testUri, Buffer.from(tests.testCode, 'utf8'));
  await TraeAPI.window.showTextDocument(testUri);
});

Git統合

typescript
// Git操作とAI機能を統合
TraeAPI.commands.registerCommand('ai.generateCommitMessage', async () => {
  const gitExtension = TraeAPI.extensions.getExtension('vscode.git');
  if (!gitExtension) return;

  const git = gitExtension.exports.getAPI(1);
  const repository = git.repositories[0];
  
  if (!repository) return;

  const diff = await repository.diff();
  const commitMessage = await aiService.generateCommitMessage({
    diff,
    style: 'conventional-commits',
    maxLength: 72
  });

  // コミットメッセージを設定
  repository.inputBox.value = commitMessage.message;
});

CI/CD統合

typescript
// CI/CDパイプラインでAI機能を使用
const cicdIntegration = {
  async analyzeCodeQuality(changedFiles: string[]) {
    const results = [];
    
    for (const file of changedFiles) {
      const content = await TraeAPI.workspace.fs.readFile(TraeAPI.Uri.file(file));
      const analysis = await aiService.reviewCode({
        code: content.toString(),
        language: getLanguageFromFile(file),
        criteria: {
          codeQuality: true,
          security: true,
          performance: true
        }
      });
      
      results.push({
        file,
        score: analysis.overallScore,
        issues: analysis.issues
      });
    }
    
    return results;
  },

  async generateReleaseNotes(commits: any[]) {
    const releaseNotes = await aiService.generateReleaseNotes({
      commits,
      format: 'markdown',
      includeBreakingChanges: true,
      groupByType: true
    });
    
    return releaseNotes.content;
  }
};

APIリファレンス

AIService

typescript
interface AIService {
  // コード生成
  generateCode(options: CodeGenerationOptions): Promise<CodeGenerationResult>;
  refactorCode(options: RefactoringOptions): Promise<RefactoringResult>;
  
  // コード分析
  explainCode(options: CodeExplanationOptions): Promise<CodeExplanation>;
  reviewCode(options: CodeReviewOptions): Promise<CodeReview>;
  analyzeError(options: ErrorAnalysisOptions): Promise<ErrorAnalysis>;
  
  // ドキュメント生成
  generateDocumentation(options: DocumentationOptions): Promise<Documentation>;
  generateTests(options: TestGenerationOptions): Promise<TestGeneration>;
  
  // 言語変換
  convertLanguage(options: LanguageConversionOptions): Promise<LanguageConversion>;
  
  // 最適化
  optimizePerformance(options: OptimizationOptions): Promise<OptimizationResult>;
  analyzeSecurityVulnerabilities(options: SecurityAnalysisOptions): Promise<SecurityAnalysis>;
  
  // 設定
  getAvailableModels(): Promise<string[]>;
  setDefaultModel(model: string): Promise<void>;
  configureModels(config: ModelConfiguration): Promise<void>;
  setCustomPrompts(prompts: CustomPrompts): Promise<void>;
  setProjectContext(context: ProjectContext): Promise<void>;
  
  // ワークフロー
  createWorkflow(definition: WorkflowDefinition): AIWorkflow;
  createAssistant(config: AssistantConfiguration): AIAssistant;
}

CodeGenerationResult

typescript
interface CodeGenerationResult {
  code: string;
  explanation: string;
  confidence: number;
  language: string;
  metadata: {
    model: string;
    tokensUsed: number;
    generationTime: number;
  };
  suggestions?: string[];
  alternatives?: string[];
}

CodeReview

typescript
interface CodeReview {
  overallScore: number; // 0-100
  issues: CodeIssue[];
  suggestions: CodeSuggestion[];
  positives: string[];
  metrics: {
    complexity: number;
    maintainability: number;
    readability: number;
    performance: number;
    security: number;
  };
}

interface CodeIssue {
  type: 'error' | 'warning' | 'info';
  category: 'performance' | 'security' | 'maintainability' | 'style';
  message: string;
  line?: number;
  column?: number;
  severity: number;
  fix?: string;
}

ベストプラクティス

  1. 適切なモデル選択: タスクに応じて最適なAIモデルを選択
  2. コンテキスト提供: より良い結果のために十分なコンテキストを提供
  3. 結果の検証: AI生成コードは必ずレビューしてから使用
  4. 段階的な統合: 小さな機能から始めて徐々に拡張
  5. エラーハンドリング: AI APIの失敗に対する適切な処理
  6. パフォーマンス考慮: 大きなコードベースでは処理時間を考慮
  7. プライバシー保護: 機密情報をAIサービスに送信しない
  8. レート制限: API使用量を監視し制限を遵守

エラーハンドリング

typescript
try {
  const result = await aiService.generateCode({
    prompt: 'HTTPサーバーを作成',
    language: 'typescript'
  });
  
  console.log(result.code);
} catch (error) {
  if (error instanceof TraeAPI.AIError) {
    switch (error.code) {
      case 'MODEL_UNAVAILABLE':
        TraeAPI.window.showErrorMessage('AIモデルが利用できません');
        break;
      case 'RATE_LIMIT_EXCEEDED':
        TraeAPI.window.showWarningMessage('レート制限に達しました');
        break;
      case 'INVALID_INPUT':
        TraeAPI.window.showErrorMessage('入力が無効です');
        break;
      case 'CONTEXT_TOO_LARGE':
        TraeAPI.window.showWarningMessage('コンテキストが大きすぎます');
        break;
      default:
        TraeAPI.window.showErrorMessage(`AI エラー: ${error.message}`);
    }
  } else {
    console.error('予期しないエラー:', error);
  }
}

パフォーマンス最適化

typescript
// AIリクエストのキャッシュ
const aiCache = new Map<string, any>();

async function cachedAIRequest<T>(
  key: string,
  requestFn: () => Promise<T>,
  ttl: number = 300000 // 5分
): Promise<T> {
  const cached = aiCache.get(key);
  if (cached && Date.now() - cached.timestamp < ttl) {
    return cached.result;
  }

  const result = await requestFn();
  aiCache.set(key, {
    result,
    timestamp: Date.now()
  });

  return result;
}

// 使用例
const explanation = await cachedAIRequest(
  `explain-${codeHash}`,
  () => aiService.explainCode({ code, language })
);

関連API

究極の AI 駆動 IDE 学習ガイド