Skip to content
Sign in

Qwen Code integration guide

AI codingUpdated: 2025-11-27

Introduction

Qwen Code (Tongyi Lingma) is Alibaba Cloud's AI coding assistant built on the Qwen models. It offers line- and function-level completion, natural language to code, unit test generation, comment generation, code explanation, developer Q&A and error diagnosis.

Key capabilities

  • 🚀 Smart completion — real-time line- and function-level completion
  • 💡 Natural language to code — describe what you want and get code
  • 🔍 Explanation and optimization — analyze logic and suggest improvements
  • 🧪 Unit test generation — produce complete test cases in one step
  • 🐛 Smart debugging — locate and fix errors quickly
  • 💬 Developer Q&A — ask programming questions any time

Why connect it to SeaWhale AI?

Through SeaWhale AI, Qwen Code gains:

  • 200+ models — GPT-4, Claude, Gemini and other top models
  • Pay as you go — no subscription, pay only for what you use
  • Automatic failover — switches models automatically to stay available
  • OpenAI-compatible — drops into your existing workflow

Supported IDEs

Qwen Code works with the major IDEs:

IDEVersionDownload
Visual Studio Code1.75.0+VSCode marketplace
JetBrains IDEs2022.1+JetBrains marketplace
IntelliJ IDEA2022.1+As above
PyCharm2022.1+As above
WebStorm2022.1+As above
GoLand2022.1+As above

Compatibility

This guide uses Visual Studio Code for its examples. The steps for JetBrains IDEs are similar.


Before you begin

Make sure you have:

  1. ✅ A supported IDE installed (the latest version is recommended)
  2. ✅ A SeaWhale AI API key (how to get one)
  3. ✅ Enough account balance to call model services
  4. ✅ Network access to the SeaWhale AI API endpoint

Important

Qwen Code uses Alibaba Cloud's own service by default. This guide walks through pointing it at SeaWhale AI instead, for a wider model choice and flexible billing.


Installation and configuration

Step 1: install the Qwen Code plugin

VSCode

Option 1: the marketplace (recommended)

  1. Open VSCode
  2. Click the Extensions icon in the activity bar (or press Ctrl+Shift+X / Cmd+Shift+X)
  3. Search for Tongyi Lingma
  4. Find the Alibaba Cloud - Tongyi Lingma extension
  5. Click Install

Option 2: the command line

bash
code --install-extension Alibaba-Cloud.tongyi-lingma

JetBrains

  1. Open IntelliJ IDEA / PyCharm / WebStorm
  2. Go to FileSettings (Windows/Linux) or Preferences (macOS)
  3. Choose PluginsMarketplace
  4. Search for Tongyi Lingma
  5. Click Install and restart the IDE

Step 2: point it at SeaWhale AI

Qwen Code defaults to Alibaba Cloud's service, so you need to change the endpoint.

VSCode

  1. Open settings

    • Click the gear icon in the bottom left → Settings
    • Or press Ctrl+, (Windows/Linux) / Cmd+, (macOS)
  2. Find the Qwen Code settings

    • Search for tongyi
    • Locate the Tongyi Lingma settings
  3. Configure the endpoint

SettingDescriptionValue
API Base URLThe SeaWhale AI API addresshttps://api.your-domain.com/v1
API KeyYour SeaWhale AI API keysk-xxxxxxxxxxxxxxxx
ModelThe model to usegpt-4 / claude-3-opus etc.
Example settings.json

You can also edit VSCode's settings.json directly:

json
{
  "tongyi.apiBaseUrl": "https://api.your-domain.com/v1",
  "tongyi.apiKey": "sk-xxxxxxxxxxxxxxxx",
  "tongyi.model": "gpt-4-turbo",
  "tongyi.enableCodeCompletion": true,
  "tongyi.enableInlineCompletion": true,
  "tongyi.temperature": 0.3,
  "tongyi.maxTokens": 2048
}

JetBrains

  1. Open FileSettingsToolsTongyi Lingma
  2. Configure:
    • API Base URL: https://api.your-domain.com/v1
    • API Key: your SeaWhale AI API key
    • Model: select or type a model ID (such as gpt-4-turbo)
  3. Click Test Connection
  4. Click OK to save

Step 3: choose a model

SeaWhale AI supports many models, each suited to different work:

Use caseRecommended modelModel IDWhy
Everyday codingGPT-3.5 Turbogpt-3.5-turboFast and inexpensive, good for completion
Complex tasksGPT-4 Turbogpt-4-turboStrong reasoning, high code quality
Code reviewClaude 3 Opusclaude-3-opusExcellent at understanding code
Python developmentDeepSeek Coderdeepseek-coderA model tuned specifically for code
Frontend workGPT-4gpt-4Broad web technology knowledge

Switching models

  • Use GPT-3.5 Turbo for completion and simple tasks — fast and cheap
  • Use GPT-4 Turbo or Claude 3 Opus for complex algorithms and design
  • See the full model list for more options

Using the main features

1. Smart code completion

Qwen Code offers line-level and function-level completion.

Line completion

As you type, Qwen Code predicts the next line:

python
# Write a comment and the code follows
# Compute the nth Fibonacci number

# Qwen Code completes:
def fibonacci(n):
    if n <= 1:
        return n
    return fibonacci(n-1) + fibonacci(n-2)

Function completion

Write a signature and a comment, and it fills in the body:

typescript
/**
 * Check whether an email address is valid
 * @param email the email address
 * @returns whether it is valid
 */
function validateEmail(email: string): boolean {
  // Qwen Code completes the implementation
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  return emailRegex.test(email)
}

Tips

  • Accept a suggestion: press Tab
  • Next suggestion: press Alt+] (Windows/Linux) or Option+] (macOS)
  • Dismiss it: keep typing or press Esc

2. Natural language to code

Describe what you want and let the model write it.

How to use it

VSCode:

  1. Select a region, or place the cursor where you want the code
  2. Press Ctrl+Shift+L (Windows/Linux) or Cmd+Shift+L (macOS)
  3. Describe what you need in the dialog
  4. The model generates the code

JetBrains:

  1. Right-click in the editor
  2. Choose Tongyi LingmaGenerate Code
  3. Type your description

Example

The request:

Create a user login endpoint that takes a username and password and returns a JWT token

The generated code:

javascript
const express = require('express')
const jwt = require('jsonwebtoken')
const router = express.Router()

router.post('/login', async (req, res) => {
  const {username, password} = req.body

  // Validate the credentials (a real project would query the database)
  if (!username || !password) {
    return res.status(400).json({error: 'Username and password are required'})
  }

  // Issue a JWT
  const token = jwt.sign({username}, process.env.JWT_SECRET, {expiresIn: '24h'})

  res.json({token, message: 'Signed in'})
})

module.exports = router

3. Explaining and optimizing code

Explain code

Select some code and use Explain Code to get a detailed walkthrough.

Shortcuts:

  • VSCode: Ctrl+Shift+E / Cmd+Shift+E
  • JetBrains: right-click → Tongyi LingmaExplain Code

Optimize code

Select code and use Optimize Code for improvement suggestions.

Example:

Before:

python
def find_max(numbers):
    max_num = numbers[0]
    for i in range(len(numbers)):
        if numbers[i] > max_num:
            max_num = numbers[i]
    return max_num

After:

python
def find_max(numbers):
    """Return the largest value in the list"""
    return max(numbers) if numbers else None

4. Generating unit tests

Qwen Code can generate tests for your functions automatically.

How to use it

  1. Place the cursor inside the function
  2. Use the shortcut or right-click → Generate Unit Test
  3. Complete test cases are generated

Example

The function:

python
def calculate_discount(price, discount_rate):
    """Calculate the discounted price"""
    if discount_rate < 0 or discount_rate > 1:
        raise ValueError("The discount rate must be between 0 and 1")
    return price * (1 - discount_rate)

The generated tests:

python
import unittest

class TestCalculateDiscount(unittest.TestCase):
    def test_normal_discount(self):
        """A typical discount"""
        self.assertEqual(calculate_discount(100, 0.2), 80)

    def test_zero_discount(self):
        """No discount"""
        self.assertEqual(calculate_discount(100, 0), 100)

    def test_full_discount(self):
        """A full discount"""
        self.assertEqual(calculate_discount(100, 1), 0)

    def test_invalid_discount_negative(self):
        """A negative discount rate"""
        with self.assertRaises(ValueError):
            calculate_discount(100, -0.1)

    def test_invalid_discount_over_one(self):
        """A discount rate above 1"""
        with self.assertRaises(ValueError):
            calculate_discount(100, 1.5)

if __name__ == '__main__':
    unittest.main()

5. Debugging and fixing errors

When your code errors, Qwen Code helps locate and fix the problem.

How to use it

  1. Click Fix on the error, or use the shortcut
  2. The model analyzes the cause and suggests a fix
  3. Apply the fix in one click

Example

The broken code:

javascript
const users = [
  {name: 'Alice', age: 25},
  {name: 'Bob', age: 30},
]

const totalAge = users.reduce((sum, user) => sum + user.age)
// TypeError: Cannot read property 'age' of undefined

The diagnosis:

Cause: reduce has no initial value, so on the first iteration sum is an
object rather than a number.

Suggested fix:

The fix:

javascript
const totalAge = users.reduce((sum, user) => sum + user.age, 0)
// Correct result: 55

6. Developer Q&A

Qwen Code includes a chat assistant for programming questions.

Opening the chat panel

VSCode:

  • Click the Qwen Code icon in the activity bar
  • Or press Ctrl+Shift+T / Cmd+Shift+T

JetBrains:

  • Click the Qwen Code icon in the right toolbar
  • Or go to ToolsTongyi Lingma Chat

Common question types

TypeExample
API usage"How do I use Python's asyncio for concurrent work?"
Troubleshooting"Why does my React component render infinitely?"
Best practices"How should I handle async errors in Node.js?"
Technology choice"Should I use MySQL or PostgreSQL?"
Code review"What security issues does this code have?"

Advanced configuration

Tuning completion parameters

You can fine-tune behavior in VSCode's settings.json:

json
{
  // Completion settings
  "tongyi.enableCodeCompletion": true, // Enable completion
  "tongyi.enableInlineCompletion": true, // Enable inline completion
  "tongyi.completionDelay": 300, // Delay in milliseconds

  // Model parameters
  "tongyi.temperature": 0.3, // Randomness (0–1)
  "tongyi.maxTokens": 2048, // Maximum generation length
  "tongyi.topP": 0.95, // Nucleus sampling

  // Behavior
  "tongyi.autoAcceptSuggestions": false, // Accept suggestions automatically
  "tongyi.showInlineReferences": true, // Show reference sources

  // Filters
  "tongyi.excludedFiles": [
    // File types to skip
    "*.log",
    "*.md",
    "node_modules/**"
  ]
}

Parameter reference

ParameterDescriptionSuggested value
temperatureControls diversity
• Lower: deterministic, good for code
• Higher: creative, good for brainstorming
0.2–0.4 (code)
0.6–0.8 (creative)
maxTokensMaximum length of a single generation1024–2048
completionDelayDelay before completion triggers (milliseconds)200–500

Optimizing token usage

How token billing works

SeaWhale AI bills per token, and different operations cost different amounts:

OperationTokensSuggestion
Line completion50–200Happens often — use a lightweight model
Function completion200–500Moderate cost, use judiciously
Code generation500–2000Describe requirements precisely
Code explanation300–800Use it only on the code that matters
Chat Q&A100–1000Keep questions specific

Ways to save tokens

Best practices

  1. Pick the right model

    • Simple completion: gpt-3.5-turbo
    • Complex tasks: gpt-4-turbo
    • Specialized code work: deepseek-coder
  2. Reduce unnecessary completions

    json
    {
      "tongyi.completionDelay": 500, // Longer delay
      "tongyi.excludedFiles": ["*.md", "*.txt"] // Skip text files
    }
  3. Write better prompts

    • ❌ Weak: "write a function"
    • ✅ Strong: "write a JavaScript function that validates an email with a regex and returns a boolean"
  4. Control the context length

    • You rarely need to pass the whole file
    • Provide only the context that matters
  5. Batch related work

    • Generate several related functions at once
    • Fewer API calls overall :::

Monitoring token usage

Check your consumption regularly:

  1. Open the SeaWhale AI console
  2. Go to UsageToken consumption
  3. Look for high-cost patterns and optimize them

FAQ

Q1: How do I switch models?

VSCode:

  1. Open settings (Ctrl+, / Cmd+,)
  2. Search for tongyi.model
  3. Change it to another model ID (such as claude-3-opus)

JetBrains:

  1. SettingsToolsTongyi Lingma
  2. Select or type a model ID in the Model dropdown

See the model list for supported models.


Q2: Completion is slow

Possible causes:

  • Network latency
  • High model load
  • Too much context

Fixes:

  1. Reduce the completion delay

    json
    {
      "tongyi.completionDelay": 200 // Down to 200ms
    }
  2. Switch to a faster model

    json
    {
      "tongyi.model": "gpt-3.5-turbo" // A lighter model
    }
  3. Limit the context

    json
    {
      "tongyi.maxContextLines": 50 // Cap the context lines
    }

Q3: How do I disable completion for certain files?

Configure exclusions in settings.json:

json
{
  "tongyi.excludedFiles": [
    "*.md", // Markdown
    "*.txt", // Text files
    "*.log", // Logs
    "node_modules/**", // Dependencies
    "dist/**", // Build output
    ".git/**" // Git internals
  ]
}

Q4: The generated code isn't good enough

Improving quality

  1. Use a stronger model

    • Move from gpt-3.5-turbo to gpt-4-turbo
    • Or use claude-3-opus for better reasoning
  2. Provide more context

    • Write clear comments describing what you want
    • Include type definitions and interfaces
    • Give example inputs and outputs
  3. Tune the generation parameters

    json
    {
      "tongyi.temperature": 0.2, // Less randomness
      "tongyi.maxTokens": 2048 // Allow longer output
    }
  4. Iterate

    • Generate a first version
    • Improve it with "Optimize Code"
    • Use "Explain Code" to check the logic :::

Q5: How do I handle API failures?

Error: 401 Unauthorized

Cause: the API key is invalid or expired.

Fix:

  • Check the API key is correct
  • Confirm your account is in good standing
  • Regenerate the API key

Error: 429 Too Many Requests

Cause: requests are too frequent.

Fix:

  • Increase completionDelay
  • Trigger completion less often
  • Increase your account quota

Error: 500 Internal Server Error

Cause: a server-side error.

Fix:

  • Retry later
  • Switch to a fallback model
  • Contact support

Q6: Which programming languages are supported?

Qwen Code supports all mainstream languages:

CategoryLanguages
BackendPython, Java, Go, Node.js, C/C++, C#, PHP, Ruby, Rust
FrontendJavaScript, TypeScript, HTML, CSS, Vue, React, Angular
MobileSwift, Kotlin, Dart (Flutter), Java (Android)
Data sciencePython (NumPy, Pandas), R, Julia, MATLAB
OtherSQL, Shell, YAML, JSON, Markdown

Best practices

1. Getting the most from completion

Completion tips

✅ Do:

  1. Write clear comments

    python
    # Binary search for a target value in a sorted array
    # Time complexity: O(log n)
    def binary_search(arr, target):
        # The model generates the right implementation from the comment
  2. Define explicit signatures

    typescript
    interface User {
      id: string;
      name: string;
      email: string;
    }
    
    // With types available, the model generates type-safe code
    function validateUser(user: User): boolean {
  3. Give example data

    javascript
    // Example input: [1, 2, 3, 4, 5]
    // Expected output: [1, 4, 9, 16, 25]
    function squareArray(numbers) {

❌ Avoid:

  1. Vague descriptions

    python
    # process data  ❌ too vague
    def process(data):
  2. Missing type information

    javascript
    function calculate(a, b) {  // ❌ numbers or strings?
  3. Meaningless names

    python
    def func1(x, y, z):  // ❌ names carry no meaning

2. Getting the most from code generation

Describe requirements the SMART way

  • Specific: spell out the details
  • Measurable: give expected inputs and outputs
  • Achievable: keep the scope reasonable
  • Relevant: match the surrounding context
  • Time-bound: state any performance requirements

Comparison

❌ A weak description:

Write a user management system

✅ A strong description:

Create an Express.js user management API with:
1. POST /users - create a user (name, email, password)
2. GET /users/:id - fetch a user
3. PUT /users/:id - update a user
4. DELETE /users/:id - delete a user
Store data in MongoDB, hash passwords with bcrypt, return JSON

3. Working as a team

Team conventions

  1. Share configuration

    • Create a shared settings.json template
    • Use the same model and parameters
    • Keep code style consistent
  2. Review the output

    • Generated code still needs human review
    • Watch for security and performance issues
    • Add the tests that matter
  3. Version control

    • Add .vscode/settings.json to .gitignore if it holds an API key
    • Manage secrets through environment variables
    • Note which code was AI-assisted
  4. Cost control

    • Monitor the team's total token usage
    • Assign different models to different roles
    • Review high-cost patterns regularly :::

4. Security

Security reminders

  1. Protect secrets

    • Never put real API keys or passwords in comments
    • Manage secrets with environment variables and config files
    • The model may reuse sensitive values it sees in context
  2. Review generated code

    • AI-generated code can contain vulnerabilities
    • Pay particular attention to SQL injection and XSS
    • Run security scanners over generated code
  3. License compliance

    • Generated code may inadvertently reproduce open-source code
    • Make sure it is compatible with your project's license
    • Do not ship unreviewed snippets
  4. Data privacy

    • Do not feed user personal data to the model
    • Be careful sending internal code to a cloud service
    • Consider a local deployment if you need to :::

Going further

1. Custom prompt templates

Save frequently used prompts as templates:

json
// .vscode/settings.json
{
  "tongyi.customPrompts": {
    "generateAPI": "Create a RESTful API with CRUD operations using the {framework} framework and {database} database",
    "addTests": "Generate complete unit tests for the following function using {testFramework}, with 90%+ coverage",
    "refactor": "Refactor the following code for performance and readability, following {language} best practices"
  }
}

2. Working alongside other tools

Compared with GitHub Copilot

FeatureQwen Code (SeaWhale AI)GitHub Copilot
Model choice200+ modelsFixed model
BillingPer tokenFixed monthly
Custom endpointSupportedNot supported

Pairs well with

  • ESLint / Prettier — format generated code automatically
  • GitLens — track the history of generated code
  • Code Spell Checker — catch typos in generated comments

3. Performance tips

Performance checklist

Caching:

json
{
  "tongyi.enableCache": true, // Enable local caching
  "tongyi.cacheExpiryTime": 3600 // Cache for an hour
}

Concurrency:

json
{
  "tongyi.maxConcurrentRequests": 3, // At most 3 in flight
  "tongyi.requestTimeout": 10000 // 10-second timeout
}

Selective enablement:

json
{
  "tongyi.enabledLanguages": [
    // Only for these languages
    "python",
    "javascript",
    "typescript"
  ]
}

Other AI coding tools

ToolPlatformsCharacteristics
Qwen CodeVSCode/JetBrainsBroad feature set
ClineVSCodePlans and runs multi-step tasks
Claude CodeCLITerminal-based, good for scripting
CursorStandalone IDEDeep integration, new editing model

Support

Getting help

We offer several support channels:

ChannelResponse timeBest for
📖 DocumentationImmediateCommon questions and usage guides
💬 Live supportWeekdays 9:00–18:00Real-time technical questions
📧 Email supportWithin 24 hoursDetailed reports and feedback
🐛 Bug reportsWithin 48 hoursBugs and feature requests

Changelog

2025-11-27

  • ✨ Added the Qwen Code integration guide
  • 📝 Improved SEO metadata
  • 🎨 Refined the document structure

© 2024 SeaWhale AI. All rights reserved.

Last updated 2025-11-27