Skip to content

Code Generation API ​

The Code Generation API provides powerful AI-driven code generation capabilities, allowing extensions to generate, modify, and refactor code automatically.

Overview ​

The Code Generation API enables you to:

  • Generate code from natural language descriptions
  • Auto-complete code snippets
  • Refactor existing code
  • Generate tests and documentation
  • Create boilerplate code
  • Transform code between languages

Basic Usage ​

Simple Code Generation ​

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

// Generate code from description
const generatedCode = await TraeAPI.ai.codeGeneration.generate({
  prompt: 'Create a function that calculates the factorial of a number',
  language: 'typescript',
  context: {
    fileName: 'math-utils.ts',
    existingCode: '// Math utility functions'
  }
});

console.log('Generated code:', generatedCode.code);
console.log('Explanation:', generatedCode.explanation);

Code Completion ​

typescript
// Get code completion suggestions
const editor = TraeAPI.window.activeTextEditor;
if (editor) {
  const position = editor.selection.active;
  const document = editor.document;
  
  const completion = await TraeAPI.ai.codeGeneration.complete({
    document: document.getText(),
    position,
    language: document.languageId,
    maxSuggestions: 5
  });
  
  // Apply the best suggestion
  if (completion.suggestions.length > 0) {
    const bestSuggestion = completion.suggestions[0];
    await editor.edit(editBuilder => {
      editBuilder.insert(position, bestSuggestion.code);
    });
  }
}

Code Refactoring ​

typescript
// Refactor selected code
async function refactorSelection() {
  const editor = TraeAPI.window.activeTextEditor;
  if (!editor || editor.selection.isEmpty) {
    return;
  }

  const selectedCode = editor.document.getText(editor.selection);
  
  const refactored = await TraeAPI.ai.codeGeneration.refactor({
    code: selectedCode,
    language: editor.document.languageId,
    refactorType: 'optimize', // 'optimize' | 'simplify' | 'modernize' | 'extract'
    instructions: 'Make this code more efficient and readable'
  });

  // Replace selected code with refactored version
  await editor.edit(editBuilder => {
    editBuilder.replace(editor.selection, refactored.code);
  });

  // Show explanation
  TraeAPI.window.showInformationMessage(
    `Refactoring complete: ${refactored.explanation}`
  );
}

Advanced Features ​

Template-based Generation ​

typescript
// Generate code using templates
const componentCode = await TraeAPI.ai.codeGeneration.generateFromTemplate({
  template: 'react-component',
  parameters: {
    componentName: 'UserProfile',
    props: ['name', 'email', 'avatar'],
    hooks: ['useState', 'useEffect'],
    styling: 'tailwind'
  },
  language: 'typescript'
});

// Generate API endpoint
const apiCode = await TraeAPI.ai.codeGeneration.generateFromTemplate({
  template: 'express-endpoint',
  parameters: {
    method: 'POST',
    path: '/api/users',
    validation: true,
    database: 'mongodb'
  },
  language: 'typescript'
});

Multi-file Generation ​

typescript
// Generate multiple related files
const projectFiles = await TraeAPI.ai.codeGeneration.generateProject({
  description: 'Create a simple todo app with React and Node.js',
  structure: {
    frontend: 'react-typescript',
    backend: 'node-express',
    database: 'mongodb',
    styling: 'tailwind'
  },
  features: ['authentication', 'crud-operations', 'real-time-updates']
});

// Create all generated files
for (const file of projectFiles.files) {
  const uri = TraeAPI.Uri.file(file.path);
  const content = Buffer.from(file.content, 'utf8');
  await TraeAPI.workspace.fs.writeFile(uri, content);
}

Test Generation ​

typescript
// Generate unit tests for a function
async function generateTests() {
  const editor = TraeAPI.window.activeTextEditor;
  if (!editor) {
    return;
  }

  const selectedCode = editor.document.getText(editor.selection);
  
  const tests = await TraeAPI.ai.codeGeneration.generateTests({
    code: selectedCode,
    language: editor.document.languageId,
    testFramework: 'jest', // 'jest' | 'mocha' | 'vitest' | 'pytest'
    testTypes: ['unit', 'edge-cases', 'error-handling'],
    coverage: 'comprehensive'
  });

  // Create test file
  const testFileName = editor.document.fileName.replace(/\.(ts|js)$/, '.test.$1');
  const testUri = TraeAPI.Uri.file(testFileName);
  const testContent = Buffer.from(tests.code, 'utf8');
  
  await TraeAPI.workspace.fs.writeFile(testUri, testContent);
  
  // Open test file
  const testDocument = await TraeAPI.workspace.openTextDocument(testUri);
  await TraeAPI.window.showTextDocument(testDocument);
}

Documentation Generation ​

typescript
// Generate documentation for code
const documentation = await TraeAPI.ai.codeGeneration.generateDocumentation({
  code: selectedCode,
  language: 'typescript',
  format: 'jsdoc', // 'jsdoc' | 'markdown' | 'sphinx' | 'rustdoc'
  includeExamples: true,
  includeTypes: true
});

// Insert documentation
const editor = TraeAPI.window.activeTextEditor;
if (editor) {
  const position = editor.selection.start;
  await editor.edit(editBuilder => {
    editBuilder.insert(position, documentation.code + '\n');
  });
}

Language Transformation ​

Code Translation ​

typescript
// Translate code between languages
const translatedCode = await TraeAPI.ai.codeGeneration.translate({
  code: pythonCode,
  fromLanguage: 'python',
  toLanguage: 'typescript',
  preserveComments: true,
  adaptIdioms: true
});

// Convert between frameworks
const convertedComponent = await TraeAPI.ai.codeGeneration.convertFramework({
  code: reactComponent,
  fromFramework: 'react',
  toFramework: 'vue',
  version: '3.x'
});

Code Modernization ​

typescript
// Modernize legacy code
const modernizedCode = await TraeAPI.ai.codeGeneration.modernize({
  code: legacyJavaScript,
  language: 'javascript',
  targetVersion: 'es2022',
  features: ['async-await', 'destructuring', 'arrow-functions', 'modules']
});

// Upgrade framework version
const upgradedCode = await TraeAPI.ai.codeGeneration.upgradeFramework({
  code: reactClassComponent,
  framework: 'react',
  fromVersion: '16.x',
  toVersion: '18.x',
  useHooks: true
});

Custom Code Generation ​

Creating Custom Generators ​

typescript
class CustomCodeGenerator {
  async generateCRUDOperations(entityName: string, fields: string[]) {
    const operations = ['create', 'read', 'update', 'delete'];
    const generatedFiles: { [key: string]: string } = {};

    for (const operation of operations) {
      const code = await TraeAPI.ai.codeGeneration.generate({
        prompt: `Generate a ${operation} operation for ${entityName} entity with fields: ${fields.join(', ')}`,
        language: 'typescript',
        context: {
          pattern: 'repository-pattern',
          database: 'mongodb',
          validation: true
        }
      });

      generatedFiles[`${entityName}${operation.charAt(0).toUpperCase() + operation.slice(1)}.ts`] = code.code;
    }

    return generatedFiles;
  }

  async generateAPIClient(openApiSpec: any) {
    const client = await TraeAPI.ai.codeGeneration.generateFromSpec({
      specification: openApiSpec,
      type: 'openapi',
      language: 'typescript',
      clientType: 'axios',
      includeTypes: true
    });

    return client;
  }
}

Batch Code Generation ​

typescript
// Generate multiple code snippets in batch
const batchResults = await TraeAPI.ai.codeGeneration.generateBatch([
  {
    prompt: 'Create a user authentication service',
    language: 'typescript',
    context: { pattern: 'service-layer' }
  },
  {
    prompt: 'Create user model with validation',
    language: 'typescript',
    context: { pattern: 'model-validation' }
  },
  {
    prompt: 'Create user controller with CRUD operations',
    language: 'typescript',
    context: { pattern: 'controller-pattern' }
  }
]);

// Process results
batchResults.forEach((result, index) => {
  console.log(`Generated code ${index + 1}:`, result.code);
});

Integration with Editor ​

Inline Code Suggestions ​

typescript
// Register inline code suggestion provider
const provider = TraeAPI.languages.registerInlineCompletionItemProvider(
  { scheme: 'file', language: 'typescript' },
  {
    async provideInlineCompletionItems(document, position, context, token) {
      const lineText = document.lineAt(position.line).text;
      const prefix = lineText.substring(0, position.character);

      if (prefix.trim().startsWith('//')) {
        // Generate code from comment
        const comment = prefix.trim().substring(2).trim();
        const generated = await TraeAPI.ai.codeGeneration.generate({
          prompt: comment,
          language: document.languageId,
          context: {
            surroundingCode: getSurroundingCode(document, position)
          }
        });

        return {
          items: [{
            insertText: '\n' + generated.code,
            range: new TraeAPI.Range(position, position)
          }]
        };
      }

      return { items: [] };
    }
  }
);

Code Actions ​

typescript
// Register code action provider for generation
const codeActionProvider = TraeAPI.languages.registerCodeActionsProvider(
  { scheme: 'file' },
  {
    async provideCodeActions(document, range, context, token) {
      const actions: TraeAPI.CodeAction[] = [];

      // Add "Generate tests" action
      const generateTestsAction = new TraeAPI.CodeAction(
        'Generate Tests',
        TraeAPI.CodeActionKind.Refactor
      );
      generateTestsAction.command = {
        command: 'myExtension.generateTests',
        title: 'Generate Tests',
        arguments: [document.uri, range]
      };
      actions.push(generateTestsAction);

      // Add "Generate documentation" action
      const generateDocsAction = new TraeAPI.CodeAction(
        'Generate Documentation',
        TraeAPI.CodeActionKind.Refactor
      );
      generateDocsAction.command = {
        command: 'myExtension.generateDocs',
        title: 'Generate Documentation',
        arguments: [document.uri, range]
      };
      actions.push(generateDocsAction);

      return actions;
    }
  }
);

API Reference ​

Generation Methods ​

generate() ​

typescript
generate(options: {
  prompt: string;
  language: string;
  context?: GenerationContext;
  maxTokens?: number;
  temperature?: number;
}): Promise<GenerationResult>;

complete() ​

typescript
complete(options: {
  document: string;
  position: Position;
  language: string;
  maxSuggestions?: number;
}): Promise<CompletionResult>;

refactor() ​

typescript
refactor(options: {
  code: string;
  language: string;
  refactorType: RefactorType;
  instructions?: string;
}): Promise<RefactorResult>;

Types ​

typescript
interface GenerationResult {
  code: string;
  explanation: string;
  confidence: number;
  suggestions?: string[];
}

interface CompletionResult {
  suggestions: CompletionSuggestion[];
  context: CompletionContext;
}

interface RefactorResult {
  code: string;
  explanation: string;
  changes: CodeChange[];
}

Best Practices ​

  1. Provide clear and specific prompts for better generation results
  2. Include relevant context (existing code, file structure, patterns)
  3. Validate generated code before applying it
  4. Use appropriate temperature settings (lower for precise code, higher for creative solutions)
  5. Handle errors gracefully when generation fails
  6. Cache frequently used generations to improve performance
  7. Respect user preferences for code style and patterns
  8. Test generated code automatically when possible

Error Handling ​

typescript
try {
  const result = await TraeAPI.ai.codeGeneration.generate({
    prompt: 'Create a complex algorithm',
    language: 'typescript'
  });
  
  // Validate generated code
  const isValid = await validateGeneratedCode(result.code);
  if (!isValid) {
    throw new Error('Generated code is invalid');
  }
  
  return result;
} catch (error) {
  if (error instanceof TraeAPI.GenerationError) {
    TraeAPI.window.showErrorMessage(`Code generation failed: ${error.message}`);
  } else if (error instanceof TraeAPI.ValidationError) {
    TraeAPI.window.showWarningMessage('Generated code needs manual review');
  } else {
    console.error('Unexpected error:', error);
  }
}

Performance Optimization ​

typescript
// Use caching for repeated generations
const cache = new Map<string, GenerationResult>();

async function generateWithCache(prompt: string, language: string) {
  const cacheKey = `${prompt}:${language}`;
  
  if (cache.has(cacheKey)) {
    return cache.get(cacheKey)!;
  }
  
  const result = await TraeAPI.ai.codeGeneration.generate({ prompt, language });
  cache.set(cacheKey, result);
  
  return result;
}

// Debounce rapid generation requests
const debouncedGenerate = debounce(async (prompt: string) => {
  return await TraeAPI.ai.codeGeneration.generate({ prompt, language: 'typescript' });
}, 300);

Your Ultimate AI-Powered IDE Learning Guide