Skip to content

khairb/ai-code-completion

Folders and files

NameName
Last commit message
Last commit date

Latest commit

ย 

History

27 Commits
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 

Repository files navigation

๐Ÿค– AI Python Code Completion for VS Code

Intelligent, context-aware code completion powered by OpenAI's GPT models (supported language: Python)

A Visual Studio Code extension that provides real-time AI-powered code completion suggestions. This extension tries to understand your code context, analyzes your intent, and generates a suggestions that you can integrate with your coding workflow.

โœจ Features

๐Ÿง  ** Context Analysis**

  • Scope-Aware Suggestions: Understands functions, classes, and modules
  • Hierarchical Context: Analyzes nested code structures for better completions
  • Error-Aware: Considers existing errors and warnings when generating suggestions
  • Python AST Parsing: Uses Tree-sitter for code structure analysis

๐ŸŽฏ User Experience

  • Ghost Text Display: Native VS Code inline completion with transparent suggestions
  • Tab to Accept: Tab key to accept suggestions
  • Real-time Updates: Suggestions update as you type

๐ŸŽฌ Demo

๐ŸŽฅ Watch Demo Video

๐Ÿ› ๏ธ Installation & Setup

Prerequisites

  • VS Code (version 1.74.0 or higher)
  • Node.js (version 16 or higher)
  • OpenAI API Key (get one at platform.openai.com)

Step 1: Clone the Repository

git clone <repository-url>
cd ai-code-completion

Step 2: Install Dependencies

npm install

Step 3: Configure Your OpenAI API Key

  1. Open VS Code Settings:

    • Press Cmd + , (Mac) or Ctrl + , (Windows/Linux)
    • Or go to Code โ†’ Preferences โ†’ Settings
  2. Search for "AI Code Completion":

    • Type "aiCodeCompletion" in the settings search box
    • You should see the "AI Code Completion" section
  3. Add your OpenAI API Key:

    • Find "AI Code Completion: OpenAI API Key"
    • Click "Edit in settings.json" or enter your API key directly
    • Your API key should start with sk-
  4. Example settings.json:

    {
      "aiCodeCompletion.openaiApiKey": "sk-your-actual-api-key-here"
    }

Step 4: Build the Extension

npm run compile

Step 5: Run in Development Mode

  • Press F5 in VS Code to launch Extension Development Host
  • Or use the "Run Extension" debug configuration

๐ŸŽฎ How to Use

Basic Usage

  1. Open a supported file (Python, JavaScript, TypeScript, or React)
  2. Place your cursor at the end of a line where you want a suggestion
  3. Wait for the ghost text suggestion to appear (transparent text)
  4. Press Tab to accept and insert the suggestion
  5. Press Escape to dismiss the suggestion

Advanced Features

๐ŸŽ›๏ธ Configuration Options

You can customize the extension behavior in VS Code settings:

{
  "aiCodeCompletion.openaiApiKey": "sk-your-api-key",
  "aiCodeCompletion.model": "gpt-4o-mini",
  "aiCodeCompletion.maxTokens": 100,
  "aiCodeCompletion.temperature": 0.2,
  "aiCodeCompletion.enableInlineCompletion": true,
  "aiCodeCompletion.triggerDelay": 500
}

๐Ÿ—๏ธ AI Architecture Deep Dive

๐Ÿค– Two-Stage AI System Overview

The extension implements a two-stage AI architecture that optimizes for speed, and quality. This approach separates the decision-making process from code generation, allowing for intelligent filtering and targeted completions.

Why Two Stages?

  • Quality Control: Ensure completions are relevant and helpful
  • Speed Optimization: Quick filtering before detailed generation
  • Context Awareness: Better understanding of user intent
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”    โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”    โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚   Completion    โ”‚โ”€โ”€โ”€โ–ถโ”‚   Completion     โ”‚โ”€โ”€โ”€โ–ถโ”‚   Completion    โ”‚
โ”‚    Advisor      โ”‚    โ”‚    Generator     โ”‚    โ”‚   Postprocessor โ”‚
โ”‚   (GPT-4o-mini) โ”‚    โ”‚   (GPT-4o-mini)  โ”‚    โ”‚                 โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜    โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜    โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
         โ”‚                       โ”‚                       โ”‚
         โ–ผ                       โ–ผ                       โ–ผ
    Plan a good            Generate the           Clean and format
    suggestion             actual code            the completion

๐ŸŽฏ Stage 1: Completion Advisor - The Intelligent Gatekeeper

The Completion Advisor acts as a pre-filter that analyzes the current coding context and decides whether a full completion generation is warranted.

What the Advisor Receives:

  • Complete Code Context: The entire document with cursor position marked using โ–ˆ character
  • Scope Information: Current function/class name and type from Python AST parsing
  • Cursor Position: Exact location with surrounding line context (previous, current, next lines)
  • Error Diagnostics: All VS Code errors and warnings in the document for context awareness

What the Advisor Processes:

The advisor performs comprehensive analysis through multiple lenses:

Code Completeness Analysis:

  • Checks for incomplete declarations, missing brackets, or syntax errors
  • Identifies empty code blocks (if, while, for, function, class) that need filling
  • Detects missing return statements or incomplete implementations
  • Evaluates whether the current scope has unfinished functionality

Intent Recognition:

  • Determines if user is declaring new variables, functions, or classes
  • Analyzes naming patterns and context to predict relevant details
  • Understands the overall purpose of the code being written
  • Identifies patterns that suggest specific completion needs

Context Evaluation:

  • Considers the current scope (function, class, or module level)
  • Evaluates surrounding code structure and patterns
  • Analyzes error messages for completion opportunities
  • Assesses the significance of the current cursor position

What the Advisor Outputs:

The advisor provides structured JSON output with three key decisions:

1. Suggestion Necessity (suggestion_needed):

  • "yes" or "no" based on comprehensive analysis
  • Includes reasoning when no suggestion is needed
  • Considers both immediate needs and broader context

2. Suggestion Size (suggestion_size):

  • "inline": Single line continuation (variable names, method calls, etc.)
  • "block": Multi-line code blocks (function bodies, class definitions, etc.)
  • Based on context analysis and user intent

3. Plain English Guidance (suggestion):

  • Detailed description of what should be completed
  • Focuses on the specific code to be added
  • Provides context about the intended functionality
  • Guides the completion generator's approach

Example Advisor Output:

{
  "suggestion_needed": "yes",
  "suggestion_size": "block",
  "suggestion": "Complete the function body by adding a loop to process the data list and return the calculated result"
}

โšก Stage 2: Completion Generator - The Code Creator

The Completion Generator is responsible for transforming the advisor's guidance into actual code completions using rich context and prompt engineering.

What the Generator Receives:

  • Advisor Guidance: Plain English description of what to complete
  • Rich Code Context: Hierarchically truncated code with full innermost scope
  • Scope Information: Complete function/class context with boundaries
  • Cursor Position: Precise location marked with โ–ˆ character
  • Size Constraint: Inline vs block completion requirement

What the Generator Processes:

The generator constructs sophisticated prompts that include:

Hierarchical Context Construction:

  • Full Innermost Scope: Complete function or class where cursor is located
  • Truncated Parent Scopes: Key parts of parent functions/classes (first/last lines)
  • Module-Level Context: Important imports, global variables, and class definitions
  • Semantic Preservation: Maintains code structure understanding while reducing tokens

What the Generator Outputs:

The generator produces raw completion text that includes:

Code Completion:

  • Code that fits the cursor position
  • Proper indentation and formatting
  • Contextually appropriate syntax and patterns
  • Size-appropriate suggestions (inline or block)

Quality Characteristics:

  • Follows existing code style and patterns
  • Maintains semantic consistency with surrounding code
  • Respects Python syntax and indentation level

๐Ÿ”ง Post-Processing Pipeline - The Quality Assurance Layer

After the AI generates completion text, it goes through a post-processing pipeline to ensure quality and proper formatting.

What the Post-Processor Receives:

  • Raw AI Output: Unprocessed completion text from the generator
  • Original Context: The code that was sent to the AI
  • Cursor Position: Exact insertion point
  • Size Constraint: Whether it should be inline or block
  • Formatting Context: Indentation and style of surrounding code

What the Post-Processor Processes:

Code Cleaning:

  • Artifact Removal: Eliminates AI-generated artifacts and formatting issues
  • Syntax Validation: Ensures the completion is syntactically correct
  • Indentation Correction: Fixes any indentation issues to match context
  • Whitespace Normalization: Standardizes spacing and line breaks

Formatting Optimization:

  • Python-Specific Formatting: Ensures proper Python syntax and conventions
  • Indentation Matching: Aligns with the current code block's indentation
  • Repetition Prevention: Removes duplicate code that already exists
  • Size Enforcement: Ensures inline completions stay on one line

What the Post-Processor Outputs:

The final output is a clean, properly formatted completion that:

Ready-to-Use Code:

  • Can be inserted directly at the cursor position
  • Maintains proper indentation and formatting
  • Follows Python syntax and style guidelines

๐Ÿ”ง Development

Project Structure

src/
โ”œโ”€โ”€ extension.ts                 # Main extension entry point
โ”œโ”€โ”€ completion/
โ”‚   โ”œโ”€โ”€ completionProvider.ts    # VS Code integration layer
โ”‚   โ”œโ”€โ”€ completionAdvisor.ts     # AI advisor system
โ”‚   โ””โ”€โ”€ completionGenerator.ts   # AI completion generation
โ””โ”€โ”€ utils/
    โ”œโ”€โ”€ pythonFunctionDetector.ts # Python AST analysis
    โ”œโ”€โ”€ stringUtils.ts           # String processing utilities
    โ””โ”€โ”€ vsUtils.ts              # VS Code integration utilities

Building and Testing

# Compile TypeScript
npm run compile

# Watch for changes
npm run watch

# Debug the extension
# Press F5 in VS Code

About

A Visual Studio Code extension that provides real-time AI-powered code completion suggestions. This extension tries to understand your code context, analyzes your intent, and generates a suggestions that you can integrate with your coding workflow.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors