Skip to main content

code assistance

GitLab Duo Code Assistance

Overview

GitLab Duo provides AI-powered code assistance through Code Suggestions and Chat, helping developers write, understand, and improve code faster.

Code Suggestions

What are Code Suggestions?

Real-time AI-powered code completions that provide:

  • Single-line completions as you type
  • Multi-line code block generation
  • Context-aware suggestions based on surrounding code
  • Language-specific idioms and best practices

How It Works

Model Architecture:

  • Default Model (GitLab 18.2+): Claude Sonnet 4
  • Previous Model (GitLab 18.1): Codestral via Fireworks
  • Automatic model updates for improved performance

Context Analysis:

  • Current file content
  • Nearby code in the same file
  • Project structure
  • Language-specific patterns
  • Common coding conventions

Prompt Caching: Enabled by default to reduce latency by avoiding re-processing of cached prompts.

Supported Languages

Full support for 14+ languages:

  • C/C++
  • C#
  • Go
  • Java
  • JavaScript
  • TypeScript
  • Kotlin
  • PHP
  • Python
  • Ruby
  • Rust
  • Scala
  • Swift
  • And more

IDE Integration

VS Code

  1. Install GitLab Workflow extension
  2. Sign in with GitLab account
  3. Enable Code Suggestions in settings
  4. Start typing to see suggestions

JetBrains IDEs

  1. Install GitLab plugin
  2. Configure authentication
  3. Enable AI assistance
  4. Right-click for context menu:
    • Explain Code
    • Fix Code
    • Generate Tests
    • Refactor Code

Visual Studio

  1. Install GitLab extension
  2. Authenticate
  3. Configure Duo settings
  4. Get real-time suggestions

NeoVIM

  1. Install GitLab plugin
  2. Configure authentication
  3. Enable completion source
  4. Receive inline suggestions

GitLab Web IDE

Built-in support, no installation required.

Types of Suggestions

1. Line Completion

Complete the current line as you type.

# Type: def calculate_ # Suggestion: def calculate_total(items): # return sum(item.price for item in items)

2. Multi-Line Generation

Generate entire code blocks.

// Type: // Function to fetch user data // Suggestion: async function fetchUserData(userId) { try { const response = await fetch(`/api/users/${userId}`); if (!response.ok) { throw new Error('Failed to fetch user data'); } return await response.json(); } catch (error) { console.error('Error fetching user data:', error); throw error; } }

3. Context-Aware Completion

Suggestions based on surrounding code.

// Given class structure: class UserService { constructor(private db: Database) {} // Type: async createUser( // Suggestion: async createUser(name: string, email: string): Promise<User> { // return await this.db.users.create({ name, email }); // } }

Performance Optimization

Latency Improvements:

  • Prompt caching (default enabled)
  • Model optimization
  • Regional endpoints
  • Streaming responses

Accuracy Improvements:

  • Context window optimization
  • Language-specific fine-tuning
  • Continuous model updates
  • Feedback integration

GitLab Duo Chat

Overview

Conversational AI assistant for development tasks, accessible directly in your workflow.

Access Points

  • GitLab UI: Chat panel in sidebar
  • Web IDE: Integrated chat interface
  • VS Code: Extension sidebar
  • JetBrains: Tool window
  • Visual Studio: Extension panel

Core Capabilities

1. Code Explanation

Ask Duo to explain code snippets or functions.

Usage:

# In IDE: Right-click code † "Explain selected code"
# In Chat: Ask "Explain this code: [paste code]"

Example:

You: Explain this function
def memoize(func):
    cache = {}
    def wrapper(*args):
        if args not in cache:
            cache[args] = func(*args)
        return cache[args]
    return wrapper

Duo: This is a memoization decorator that caches function results...

2. Test Generation

Generate tests for your code.

Usage:

# In IDE: Right-click code † "Generate Tests"
# In Chat: Use /tests slash command

Example:

You: /tests
[Select code to test]

Duo: Here are unit tests for your function:

import pytest
from mymodule import calculate_total

def test_calculate_total_empty_list():
    assert calculate_total([]) == 0

def test_calculate_total_single_item():
    items = [{'price': 10.0}]
    assert calculate_total(items) == 10.0
...

Test Framework Support: Specify your preferred framework:

/tests using pytest
/tests using jest
/tests using junit

3. Code Refactoring

Get suggestions for improving code structure.

Usage:

# In IDE: Right-click code † "Refactor Code"
# In Chat: Ask "How can I refactor this?"

Example:

You: Refactor this to be more maintainable
[paste nested if/else code]

Duo: Here's a refactored version using strategy pattern...

4. Bug Fixing

Get help identifying and fixing bugs.

Usage:

# In IDE: Right-click code † "Fix Code"
# In Chat: Describe the bug

Example:

You: This function is returning None unexpectedly
[paste code]

Duo: The issue is on line 15 - you're not returning the value...

5. GitLab Feature Help

Ask questions about GitLab features.

Example:

You: How do I set up CI/CD caching?

Duo: To set up caching in GitLab CI/CD:
1. Define cache in .gitlab-ci.yml
2. Specify paths to cache
3. Use cache:key for different caches
...

Chat Commands

Slash Commands

  • /explain - Explain code or concepts
  • /tests - Generate tests
  • /refactor - Suggest refactorings
  • /fix - Help fix bugs
  • /optimize - Performance optimization suggestions

Context Sharing

Chat has access to:

  • Current file content
  • Selected code
  • Project structure
  • GitLab project metadata
  • Recent changes
  • Issue/MR context

Chat Best Practices

Effective Prompts

Good:

Explain this authentication middleware and how it validates JWT tokens

Better:

Explain this authentication middleware:
- How does it validate JWT tokens?
- What happens if validation fails?
- How can I add role-based authorization?

Iterative Refinement

Start broad, then narrow down:

1. "Explain this function"
2. "What happens in the error case?"
3. "How can I make this more testable?"

Include Context

Provide relevant information:

I'm using Python 3.11 with FastAPI. How do I implement async dependency injection for database connections?

Code Quality Features

1. Code Explanations

Snippet Explanations:

  • Right-click any code † "Explain selected snippet"
  • Get line-by-line breakdown
  • Understand complex algorithms

Error Explanations:

  • Paste error messages into chat
  • Get root cause analysis
  • Receive fix suggestions

2. Code Review Assistance

Automated Reviews:

  • AI reviews all non-draft MRs (Beta, GitLab 17.10+)
  • Identifies potential bugs
  • Suggests improvements
  • Checks best practices

Manual Review Support:

  • Ask Duo about code changes
  • Get security analysis
  • Review complexity metrics

3. Documentation Generation

Generate documentation for code:

You: Generate docstring for this function
def process_payment(amount, currency, user_id):
    # implementation

Duo:
def process_payment(amount: float, currency: str, user_id: int) -> dict:
    """
    Process a payment transaction for a user.

    Args:
        amount: Payment amount in specified currency
        currency: Three-letter currency code (e.g., 'USD', 'EUR')
        user_id: Unique identifier for the user

    Returns:
        dict: Transaction result with status and transaction_id

    Raises:
        ValueError: If amount is negative or currency is invalid
        PaymentError: If payment processing fails
    """

Advanced Features

1. Multi-File Context

Duo can consider multiple files when making suggestions:

# In file1.py
class User:
    def __init__(self, name, email):
        self.name = name
        self.email = email

# In file2.py - Duo suggests:
def create_user_from_dict(data):
    return User(data['name'], data['email'])

2. Framework-Specific Suggestions

Duo understands popular frameworks:

React:

// Type: const UserProfile // Suggestion: const UserProfile = ({ user }) => { return ( <div className="user-profile"> <h2>{user.name}</h2> <p>{user.email}</p> </div> ); };

Django:

# Type: class Article(models.Model): # Suggestion: class Article(models.Model): title = models.CharField(max_length=200) content = models.TextField() author = models.ForeignKey(User, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title

3. API Integration Suggestions

Generate API client code:

You: Create a function to call the GitHub API to get user repos

Duo:
async function getUserRepos(username) {
  const response = await fetch(
    `https://api.github.com/users/${username}/repos`,
    {
      headers: {
        'Accept': 'application/vnd.github.v3+json'
      }
    }
  );

  if (!response.ok) {
    throw new Error(`GitHub API error: ${response.status}`);
  }

  return await response.json();
}

Configuration

Enable/Disable Features

Group Level:

Settings † GitLab Duo † Enable Code Suggestions

Project Level:

Settings † GitLab Duo † Override group settings

User Level:

Preferences † GitLab Duo † Personal settings

Model Selection

Available: GitLab 18.4+

Select models at group level:

Group † Settings † GitLab Duo † Model Selection

Choose models for:

  • Code Suggestions
  • Chat
  • Code Review
  • Other features

Performance Tuning

Adjust suggestion frequency:

  • More frequent: Lower latency, more API calls
  • Less frequent: Higher latency, fewer API calls

Context window size:

  • Larger: More accurate, slower
  • Smaller: Less accurate, faster

Troubleshooting

No Suggestions Appearing

  1. Check feature is enabled
  2. Verify authentication
  3. Ensure network connectivity
  4. Check IDE extension is up-to-date

Irrelevant Suggestions

  1. Provide more context
  2. Add comments describing intent
  3. Use more descriptive names
  4. Check language mode in IDE

Slow Performance

  1. Check network latency
  2. Verify prompt caching is enabled
  3. Consider reducing context window
  4. Check for IDE conflicts

Privacy and Security

What Data is Sent?

  • Current file content (partial)
  • Surrounding code context
  • Language and framework info
  • Project metadata (minimal)

What Data is NOT Sent?

  • Full repository contents
  • Secrets or credentials
  • Unrelated files
  • User personal data

Data Retention

  • Default: Not used for model training
  • Configurable retention policies
  • Self-hosted options available

Usage Metrics

Track team adoption and usage:

Duo Analytics Dashboard:

  • Suggestion acceptance rate
  • Chat usage frequency
  • Most used features
  • Team-wide trends
  • ROI metrics

Cost Considerations

Included with Subscription

Premium/Ultimate (GitLab 18.0+):

  • Code Suggestions: Unlimited
  • Duo Chat: Unlimited
  • No per-request charges

Duo Pro ($19/user/month):

  • All features included
  • Unlimited usage
  • No hidden fees

Self-Hosted Costs

  • Infrastructure costs (compute, storage)
  • Model hosting fees (if cloud-based)
  • Network bandwidth
  • Maintenance overhead

Best Practices

  1. Accept Good Suggestions: Train the model by accepting relevant suggestions
  2. Provide Context: Add comments to guide suggestions
  3. Iterate: Refine prompts if first suggestion isn't perfect
  4. Use Chat for Complex Tasks: Code Suggestions for typing, Chat for planning
  5. Review Generated Code: Always review and test AI-generated code
  6. Combine with Testing: Generate tests alongside implementation
  7. Document Intent: Use comments to improve context
  8. Stay Language-Idiomatic: Duo respects language conventions

Next Steps