How to Debug Issues with Qwen-Agent: A Complete Troubleshooting Guide

Enable DEBUG logging via logger.setLevel('DEBUG') and trace failures through the agent runtime, LLM wrapper, and utility layers to rapidly identify root causes in Qwen-Agent.

Qwen-Agent is a modular agent framework built on large language models that routes messages between users, tools, and LLMs. When you need to debug issues with Qwen-Agent, you will typically trace problems through three architectural layers: the core runtime that handles message routing, the LLM interface that manages retries and caching, and the utility layer that provides logging and error formatting.

Understanding Qwen-Agent's Debug Architecture

Debugging Qwen-Agent requires familiarity with its three-layer architecture. Each layer exposes specific entry points where errors surface and where you can inject logging.

Core Runtime Layer

The core runtime lives in qwen_agent/agent.py and manages the agent's execution loop, tool registration, and message dispatch. Key sections include:

  • Lines 31-73: The run loop and tool call handling
  • Lines 88-103: Tool initialization and the _call_tool method where "Tool X does not exist" errors originate

When an agent fails to invoke a tool or enters an infinite loop, the traceback will point to these sections.

LLM Interface Layer

The LLM abstraction resides in qwen_agent/llm/base.py and wraps various model backends (OpenAI, DashScope, Transformers). This layer implements:

  • Lines 56-89: Retry logic, caching, and token-budget truncation
  • Lines 108-124: Exponential back-off logic in retry_model_service and retry_model_service_iterator
  • Lines 642-665: The _truncate_input_messages_roughly function that trims conversations exceeding context windows

Errors such as ModelServiceError, timeouts, or "maximum context length" exceptions originate here.

Utility and Tooling Layer

Helper functions and logging utilities live in qwen_agent/utils/utils.py and qwen_agent/log.py:

  • print_traceback (lines 86-92 in utils/utils.py): Formats the last three frames of exceptions and logs them at the appropriate level
  • Centralized logger (log.py lines 15-33): A single logger instance used across all components

Individual tools (e.g., code_interpreter, web_search) also log their own progress in qwen_agent/tools/.

Enabling Debug Logging in Qwen-Agent

All components use the single logger instance defined in qwen_agent/log.py. To obtain verbose output including timestamps, file names, and line numbers, adjust the logging level before running your agent:

from qwen_agent.log import logger

# Enable most verbose logging

logger.setLevel('DEBUG')

# Or use INFO for default verbosity

logger.setLevel('INFO')

When DEBUG is enabled, the logger prints every tool invocation, LLM request, cache lookup, and retry attempt. This is the first step in any debugging session.

Step-by-Step Debugging Workflow

Follow this systematic approach to diagnose failures in Qwen-Agent applications.

1. Enable Detailed Logging

Start every debugging session by setting the logger to DEBUG level. This reveals the exact line numbers where failures occur and shows the full content of messages passed between components.

2. Identify the Failing Component

Check the log output to determine whether the error originates in the agent runtime or the LLM interface:

  • Agent-level errors: Look for messages like "Tool XYZ does not exist" originating from Agent._call_tool in agent.py (lines 88-103).
  • LLM-level errors: Look for ModelServiceError or timeout messages from BaseChatModel.chat in base.py (lines 56-89).

3. Inspect the Exception Trace

When tools fail or LLM calls error out, Qwen-Agent uses the print_traceback utility (lines 86-92 in utils/utils.py) to format the last three frames. If you see a generic message like "An error occurred when calling tool …", scroll up in the logs to find the formatted traceback that reveals the underlying exception.

4. Check Cache and Retry Behavior

  • Cache: The BaseChatModel constructor creates a disk cache (diskcache.Cache) when cache_dir is supplied. If the cache library is missing, it is silently disabled with a warning (lines 98-105 in base.py). Verify that diskcache is installed (pip install diskcache) or disable caching to rule out stale data.
  • Retry: Exponential back-off logic lives in retry_model_service (lines 108-124 in base.py). If you suspect transient network errors, increase max_retries in your model configuration.

5. Validate Input Token Size

If conversations are truncated or you receive "maximum context length" errors, examine the _truncate_input_messages_roughly function (lines 642-665 in base.py). You can increase DEFAULT_MAX_INPUT_TOKENS in qwen_agent/settings.py or shorten the user prompt to fit within the model's context window.

6. Inspect Tool-Specific Diagnostics

Each tool logs its own progress. For example, the code interpreter logs Docker image handling at lines 184-210 in code_interpreter.py. If a specific tool fails, consult its source file in qwen_agent/tools/ for additional logger.debug, logger.info, or logger.warning statements.

Common Debugging Scenarios and Solutions

Tool Registration Failures

If you encounter "Tool X does not exist" errors in the logs, the failure originates in Agent._init_tool or Agent._call_tool (lines 88-103 in agent.py). This indicates the tool name is not registered in the TOOL_REGISTRY defined in qwen_agent/tools/__init__.py. Verify that the tool name in your function_list parameter matches the registered name exactly.

ModelServiceError and Retry Logic

ModelServiceError exceptions bubble up through BaseChatModel._chat and the retry_model_service wrapper (lines 78-90 and 108-124 in base.py). The error code determines the behavior: 400 indicates a bad request (e.g., malformed JSON or invalid parameters) that will not retry, while other codes trigger exponential back-off. Check the error code in the logs to determine if you need to fix the request payload or simply increase max_retries for transient network issues.

Context Length Truncation Issues

When conversations exceed the model's token limit, the _truncate_input_messages_roughly function (lines 642-665 in base.py) trims the message history. If you see "maximum context length" errors or notice that earlier messages disappear from the conversation, examine the debug logs for entries showing ALL tokens: X, Available tokens: Y. You can increase the token budget by modifying DEFAULT_MAX_INPUT_TOKENS in qwen_agent/settings.py or by shortening the input prompt.

Cache and Memory Problems

The LLM wrapper uses diskcache.Cache when a cache_dir is provided (lines 98-105 in base.py). If the diskcache library is not installed, caching is silently disabled with a warning. To rule out stale cache entries causing unexpected responses, either install diskcache (pip install diskcache) or remove the cache_dir parameter from your model configuration. For memory-related issues, the Memory class in memory.py (line 130) logs queries and results that you can inspect when vector store retrieval fails.

Summary

  • Enable DEBUG logging immediately using logger.setLevel('DEBUG') from qwen_agent/log.py to expose timestamps, file names, and line numbers for every operation.
  • Trace failures through three layers: the core runtime (agent.py), the LLM interface (llm/base.py), and utility helpers (utils/utils.py).
  • Inspect tool errors in Agent._call_tool (lines 88-103) and verify tool names against the TOOL_REGISTRY.
  • Diagnose LLM failures by examining ModelServiceError codes in BaseChatModel (lines 78-90) and adjusting max_retries or fixing malformed requests.
  • Resolve context truncation by monitoring _truncate_input_messages_roughly (lines 642-665) and adjusting DEFAULT_MAX_INPUT_TOKENS in settings.py.

Frequently Asked Questions

How do I enable verbose logging in Qwen-Agent?

Import the centralized logger from qwen_agent/log.py and set its level to DEBUG. This activates detailed output across all components, including timestamps, source file names, and line numbers for every tool invocation, LLM request, and retry attempt.

What does the "Tool X does not exist" error mean?

This error originates in Agent._init_tool or Agent._call_tool within qwen_agent/agent.py (lines 88-103). It indicates that the tool name specified in your function_list does not match any entry in the TOOL_REGISTRY defined in qwen_agent/tools/__init__.py. Verify the tool name spelling and registration.

How can I fix ModelServiceError timeouts?

ModelServiceError exceptions bubble up through BaseChatModel._chat in qwen_agent/llm/base.py. Check the error code in the logs: a 400 code indicates a malformed request that will not retry, while other codes trigger exponential back-off. For transient network issues, increase the max_retries parameter in your model configuration.

Why is my conversation being truncated?

When input exceeds the model's context window, the _truncate_input_messages_roughly function in qwen_agent/llm/base.py (lines 642-665) trims the message history. You will see log entries showing token counts versus available tokens. To prevent truncation, increase DEFAULT_MAX_INPUT_TOKENS in qwen_agent/settings.py or shorten your input prompts.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →