Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/QwenLM/qwen-code/llms.txt

Use this file to discover all available pages before exploring further.

Overview

Subagents are specialized AI agents that can be delegated specific tasks. They operate independently from the main agent, allowing for:
  • Parallel execution of multiple tasks
  • Domain specialization with focused instructions
  • Isolated reasoning for complex problems
  • Reduced context pollution in the main conversation
Think of subagents as coworkers you delegate work to - each with their own expertise and focus.

How Subagents Work

1

Task Delegation

The main agent identifies a subtask suitable for delegation and invokes the task tool.
2

Subagent Initialization

A specialized agent is spawned with:
  • The specific task description
  • Relevant context from the main conversation
  • Access to the same tools as the main agent
  • Independent conversation history
3

Independent Execution

The subagent:
  • Reasons about the task independently
  • Calls tools as needed
  • Builds its own conversation context
  • Requests approvals separately (in default mode)
4

Result Return

When complete, the subagent returns:
  • Task results
  • Any artifacts created
  • Summary of actions taken
  • Token usage statistics
5

Main Agent Continues

The main agent receives the results and continues with the overall task.

Using Subagents

Natural Language

The AI automatically delegates when appropriate:
> Build a REST API with authentication, database, and tests

I'll break this down into specialized tasks:

1. Delegating to subagent: Design database schema
   ➜ Subagent analyzing requirements...
   ➜ Created schema.sql
   ✓ Subagent complete

2. Delegating to subagent: Implement authentication
   ➜ Subagent building auth module...
   ➜ Created src/auth/
   ✓ Subagent complete

3. Delegating to subagent: Create API endpoints
   ➜ Subagent implementing REST routes...
   ➜ Created src/api/
   ✓ Subagent complete

4. Delegating to subagent: Write integration tests
   ➜ Subagent writing test suite...
   ➜ Created tests/integration/
   ✓ Subagent complete

All components complete! The API is ready.

Explicit Delegation

You can also use the /agents command:
# Create a specialized subagent
/agents create
This opens a configuration dialog where you specify:
  • Name: Identifier for this subagent type
  • Instructions: Specialized system prompt
  • Tools: Which tools this agent can use
  • Model: Specific model for this agent (optional)

Subagent Types

Built-in Subagent Patterns

Purpose: Analyze code for issuesInstructions:
You are a code reviewer focused on:
- Security vulnerabilities
- Performance issues
- Code style consistency
- Best practices

Provide specific, actionable feedback.
Tools: read, grep, glob, web_fetch (read-only)Usage:
> Review the auth module for security issues

Delegating to code-reviewer subagent...

Managing Subagents

Creating Custom Subagents

# Open subagent creator
/agents create
Configuration example:
{
  "name": "api-generator",
  "description": "Generates REST API endpoints from specifications",
  "instructions": [
    "You are an API generator specialist.",
    "Given an API specification, you create:",
    "- Express/Fastify routes",
    "- Request validation schemas",
    "- OpenAPI documentation",
    "- Basic integration tests",
    "",
    "Follow RESTful conventions and the project's existing patterns."
  ],
  "tools": [
    "read",
    "grep",
    "glob",
    "write_file",
    "edit",
    "bash"
  ],
  "model": "gemini-2.5-pro",
  "approvalMode": "auto-edit"
}

Managing Existing Subagents

# View and manage subagents
/agents manage
Actions available:
  • View: See subagent configuration
  • Edit: Modify instructions or settings
  • Delete: Remove a subagent
  • Duplicate: Copy and customize an existing subagent
  • Export: Save subagent to a file
  • Import: Load subagent from a file

Sharing Subagents

Subagent configurations are stored in:
~/.qwen/subagents/
  ├── code-reviewer.json
  ├── test-writer.json
  └── api-generator.json
Share with team:
# Export to project
cp ~/.qwen/subagents/api-generator.json .qwen/subagents/

# Team members automatically load project subagents

Subagent Behavior

Independent Context

Each subagent has its own conversation history:
Main Agent:
  User: Build a full-stack app
  Assistant: Breaking this into tasks...
  
  Subagent "backend":
    Task: Create Express API with auth
    Reasoning: Need to set up Express, middleware, routes...
    Tool: write_file("src/server.ts", ...)
    Tool: write_file("src/auth.ts", ...)
    Result: API created with auth endpoints
  
  Subagent "frontend":
    Task: Create React app with login
    Reasoning: Need React, routing, auth hooks...
    Tool: write_file("src/App.tsx", ...)
    Tool: write_file("src/hooks/useAuth.ts", ...)
    Result: React app created with login flow
  
  Assistant: Both backend and frontend complete!

Tool Access

Subagents can use the same tools as the main agent:
  • read - Read files
  • write_file - Create files
  • edit - Modify files
  • glob - Find files
  • ls - List directories

Approval Modes

Subagents respect the global approval mode but can have overrides:
{
  "name": "safe-analyzer",
  "approvalMode": "plan",  // Always read-only
  "tools": ["read", "grep", "glob"]
}
{
  "name": "test-automator",
  "approvalMode": "auto-edit",  // Auto-approve edits only
  "tools": ["read", "write_file", "edit", "bash"]
}

Nested Subagents

Subagents can delegate to other subagents:
Main: Build a microservices architecture
  └─ Subagent "architect": Design the system
      ├─ Subagent "api-gateway": Design gateway
      ├─ Subagent "service-auth": Design auth service
      └─ Subagent "service-data": Design data service
Nesting is limited to prevent infinite recursion:
{
  "maxNestingDepth": 3  // Default: 2 levels deep
}

Monitoring Subagents

In Interactive Mode

Subagent activity is displayed with indentation:
➜ Main: Analyzing the codebase...
  ➜ Subagent [security]: Checking for vulnerabilities...
    ✓ Tool: grep("password", "**/*.ts")
    ✓ Tool: read("src/auth.ts")
  ✓ Subagent [security]: Found 2 issues
  
  ➜ Subagent [performance]: Analyzing hot paths...
    ✓ Tool: grep("setTimeout", "**/*.ts")
    ✓ Tool: read("src/polling.ts")
  ✓ Subagent [performance]: Found 3 optimizations
✓ Main: Analysis complete

Stats and Metrics

# View subagent usage
/stats tools
Shows:
  • Number of subagent invocations
  • Average duration per subagent
  • Token usage per subagent type
  • Success/failure rates

Use Cases

Scenario: Building multiple independent features
> Add user profiles, notifications, and search

Main agent delegates:
- Subagent 1: User profiles (works on profile components)
- Subagent 2: Notifications (works on notification system)
- Subagent 3: Search (works on search functionality)

All three work in parallel, then results are integrated.
Scenario: Complex refactoring with multiple phases
> Refactor to use TypeScript and modern React

Phase 1 - Subagent "analyzer": Analyze current code
Phase 2 - Subagent "ts-converter": Convert to TypeScript
Phase 3 - Subagent "react-updater": Update to modern React
Phase 4 - Subagent "test-updater": Update tests

Each phase's subagent has specialized knowledge.
Scenario: Comprehensive code review
> Review this PR thoroughly

Delegates to specialized reviewers:
- Subagent "security": Security analysis
- Subagent "performance": Performance review
- Subagent "style": Style and conventions
- Subagent "tests": Test coverage analysis

Main agent synthesizes all feedback.
Scenario: Creating comprehensive docs
> Document the entire API

Main agent delegates by module:
- Subagent: Document auth module
- Subagent: Document database module
- Subagent: Document API routes
- Subagent: Create usage examples

Each subagent focuses on one area deeply.

Configuration

Project-Level Subagents

// .qwen/subagents/custom-reviewer.json
{
  "name": "custom-reviewer",
  "description": "Reviews code according to our team standards",
  "instructions": [
    "You are a code reviewer for our team.",
    "Check for:",
    "- Our custom ESLint rules",
    "- Proper error handling patterns",
    "- Test coverage",
    "- Documentation completeness"
  ],
  "tools": ["read", "grep", "bash"],
  "approvalMode": "plan"
}

Global Settings

// ~/.qwen/settings.json
{
  "subagents": {
    "maxConcurrent": 4,
    "maxNestingDepth": 2,
    "defaultModel": "gemini-2.5-flash",
    "inheritApprovalMode": true,
    "enabled": [
      "code-reviewer",
      "test-writer",
      "docs-writer"
    ]
  }
}

Advanced Features

Subagent Communication

Subagents can pass data between each other:
{
  "name": "coordinator",
  "instructions": [
    "Delegate tasks and coordinate results.",
    "Pass data between subagents as needed."
  ],
  "allowSubagentCommunication": true
}

Custom Models per Subagent

{
  "name": "fast-linter",
  "model": "gemini-2.5-flash",  // Fast model for simple tasks
  "instructions": ["Run linting checks"]
}
{
  "name": "deep-analyzer",
  "model": "gemini-2.5-pro",  // Powerful model for complex analysis
  "instructions": ["Analyze architecture and suggest improvements"]
}

Resource Limits

{
  "name": "bounded-task",
  "maxTokens": 10000,
  "maxTurns": 5,
  "timeout": 60000  // 60 seconds
}

Troubleshooting

Problem: Main agent isn’t delegating to subagents.Solutions:
  • Make the task more complex (simple tasks don’t need delegation)
  • Explicitly mention using specialized agents
  • Check that subagents are enabled in settings
  • Ensure the task matches subagent capabilities
Problem: Everything is delegated, making things slower.Solutions:
  • Adjust delegation threshold in settings
  • Be more specific in prompts
  • Disable some subagents temporarily
  • Use simpler prompts for simple tasks
Problem: Multiple subagents editing the same files.Solutions:
  • More specific task delegation
  • Use sequential rather than parallel delegation
  • Define clear boundaries in subagent instructions
  • Let main agent coordinate conflicts
Problem: Subagents consuming too many tokens.Solutions:
  • Set maxTokens per subagent
  • Use faster models for simple subagents
  • Limit nesting depth
  • Reduce maxConcurrent subagents

Best Practices

  1. Clear boundaries: Define what each subagent should (and shouldn’t) do
  2. Specialized instructions: Make subagents experts in narrow domains
  3. Limit tools: Only give subagents the tools they need
  4. Set resource limits: Prevent runaway subagents with timeouts and token limits
  5. Test subagents: Try them with specific prompts before relying on them
  6. Monitor usage: Check stats to optimize subagent configuration
  7. Version control: Keep subagent configs in your repo for team sharing
  8. Start simple: Begin with basic subagents, add complexity as needed

Next Steps

Skills System

Combine subagents with skills for powerful workflows

Approval Modes

Configure approval for subagent actions

Session Commands

Use /agents commands to manage subagents

Configuration

Advanced subagent configuration options