How to Use Qwen-Agent for Data Analysis: Building LLM-Powered Analytics with ReAct and Code Interpreter
Qwen-Agent enables autonomous data analysis by combining a ReAct-style agent with a sandboxed Code Interpreter tool, allowing large language models to execute Python code, manipulate datasets, and generate visualizations through a structured reasoning loop.
Qwen-Agent is an open-source framework developed by Alibaba Cloud for building LLM-driven assistants with tool-calling capabilities. When using Qwen-Agent for data analysis, you leverage the ReActChat agent class to orchestrate a reasoning loop that breaks complex questions into executable Python steps, making it possible to perform end-to-end analytics on CSV files and other data sources without writing manual scripts.
Core Components for Data Analysis
Understanding the architecture helps you customize the behavior and debug issues effectively. The framework relies on three primary components working in concert:
ReActChat Agent
The ReActChat class, located in qwen_agent/agents/react_chat.py, implements the ReAct (Reasoning and Acting) prompting pattern. This agent orchestrates the conversation loop, constructs prompts containing tool descriptions, and manages the iterative process of reasoning and tool invocation until it reaches a final answer.
CodeInterpreter Tool
The CodeInterpreter class in qwen_agent/tools/code_interpreter.py provides a sandboxed Python execution environment. When the agent decides data manipulation is required, this tool receives Python code strings, executes them in an isolated Docker-based environment, and returns stdout results or generated files (such as matplotlib charts).
FnCallAgent Base Class
FnCallAgent in qwen_agent/agents/fncall_agent.py serves as the foundation for function-calling agents. It handles generic tool registration, LLM configuration, and message formatting utilities that ReActChat inherits and extends.
How the ReAct Loop Works
The data analysis workflow follows a deterministic reasoning loop implemented in ReActChat._run (lines 73-99 of the source). Understanding this flow helps you predict agent behavior:
-
Prompt Construction – The agent builds a system prompt listing available tools, including the
code_interpreterdescription and usage syntax. -
LLM Generation – The model receives the conversation history and generates a response potentially containing
ActionandAction Inputblocks. -
Tool Detection – The
_detect_toolmethod parses the LLM output to identify if a tool call is requested. -
Execution – If code execution is needed,
_call_tooldispatches the Python code to theCodeInterpreter, which runs in a sandbox and returns observations. -
Iteration – The observation (results or error messages) is appended to the prompt, and the loop repeats until the model generates a final answer without requesting further actions.
This ReAct pattern allows the LLM to break complex analysis requests into discrete steps, such as loading a CSV, computing summary statistics, and plotting trends, executing each step sequentially while maintaining context.
Implementation Examples
The repository provides a complete reference implementation in examples/react_data_analysis.py. Below are practical patterns extracted from this example.
Minimal Script for CSV Analysis
This script initializes a ReActChat agent with the Code Interpreter and processes a stock price CSV file. The function_list=["code_interpreter"] parameter registers the tool with the agent, while the message format allows you to reference local files that the interpreter can access.
import os
from pprint import pprint
from typing import Optional
from qwen_agent.agents import ReActChat
ROOT_RESOURCE = os.path.join(os.path.dirname(__file__), "resource")
def init_agent():
llm_cfg = {
"model": "qwen-max",
"model_server": "dashscope",
"api_key": os.getenv("DASHSCOPE_API_KEY"),
}
return ReActChat(llm=llm_cfg, function_list=["code_interpreter"])
def run_query(
query: str = "Show the first 5 rows of the CSV and plot the closing price",
file: Optional[str] = os.path.join(ROOT_RESOURCE, "stock_prices.csv"),
):
bot = init_agent()
messages = [
{"role": "user", "content": [{"text": query}, {"file": file}]}
]
for response in bot.run(messages):
pprint(response, indent=2)
if __name__ == "__main__":
run_query()
Key implementation details:
- The
llm_cfgdictionary specifies model credentials and server endpoints. - File references use a structured content format:
[{"text": query}, {"file": file_path}]. - The
bot.run(messages)method returns a generator that streams partial responses, allowing real-time observation of the reasoning process.
Interactive Terminal Interface
For conversational data exploration, extend the pattern to maintain message history between queries. This approach accumulates context, allowing you to ask follow-up questions about previously loaded data.
def app_tui():
bot = init_agent()
messages = []
while True:
query = input("User question: ").strip()
file = input("File path (empty for none): ").strip()
if not query:
continue
if file:
content = [{"text": query}, {"file": file}]
else:
content = query
messages.append({"role": "user", "content": content})
for resp in bot.run(messages):
print("Bot:", resp)
# Extend history with assistant responses for multi-turn conversations
messages.extend(resp)
Web Interface with Gradio
For non-technical users, deploy the agent through a web UI using the built-in WebUI wrapper. This configuration includes prompt suggestions and file upload capabilities.
from qwen_agent.gui import WebUI
def app_gui():
bot = init_agent()
chatbot_cfg = {
"prompt.suggestions": [
{
"text": "Show the first rows and plot price trend",
"files": [os.path.join(ROOT_RESOURCE, "stock_prices.csv")]
},
"Draw a histogram of a column"
]
}
WebUI(bot, chatbot_config=chatbot_cfg).run()
Summary
- ReActChat in
qwen_agent/agents/react_chat.pyprovides the reasoning loop that enables multi-step data analysis. - CodeInterpreter in
qwen_agent/tools/code_interpreter.pyexecutes Python code safely in a sandboxed environment. - Initialize agents by passing
function_list=["code_interpreter"]to enable data processing capabilities. - Structure user messages with file references using the content array format to allow the interpreter to access datasets.
- The agent streams responses via
bot.run(), allowing you to observe the reasoning and code execution steps in real-time. - Extend functionality by inheriting from
FnCallAgentor adding custom tools to thefunction_list.
Frequently Asked Questions
What is the ReAct pattern and why does it matter for data analysis?
ReAct (Reasoning and Acting) is a prompting technique that alternates between thought processes and tool executions. For data analysis, this means the LLM can reason about what operations are needed (e.g., "I need to load this CSV and check for null values") before writing and executing the actual code. This structured approach reduces errors compared to generating code directly without intermediate reasoning steps.
Is code execution safe in Qwen-Agent?
Yes. The Code Interpreter runs Python code in an isolated Docker-based sandbox environment, not in the host process. The LLM generates code strings, but execution only occurs within the sandboxed tool, preventing unauthorized file system access or system-level operations outside the designated environment.
Can I use Qwen-Agent with local or open-source models instead of DashScope?
Absolutely. The llm_cfg configuration accepts any OpenAI-compatible API endpoint. Set model_server to your local server URL (e.g., "http://localhost:8000/v1") and adjust the model name accordingly. The framework is model-agnostic as long as the endpoint supports function calling or tool use capabilities.
How do I add custom tools beyond the Code Interpreter?
Create a new tool class using the @register_tool('tool_name') decorator, following the pattern in qwen_agent/tools/code_interpreter.py. Implement the _run method to handle your specific logic (e.g., database queries or API calls). Then include the tool name in the function_list parameter when initializing your agent. The FnCallAgent base class automatically registers the tool and includes its description in the system prompt.
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:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →