Hands-On Lab: Building Autonomous Code-Optimizing Agents with Qwen 3.7 Max
This hands-on blog demonstrates how to build a modular Code-Optimizing Agent using Alibaba Cloud Qwen 3.7 Max. It covers environment setup, API integration, a reusable Python agent runner for handling responses and reasoning traces, and a multi-turn workflow that analyzes, optimizes, and self-corrects code. The blog also highlights how preserving the model's reasoning across interactions improves context retention, accuracy, and overall agent performance.
GENERATIVE AIALIBABA CLOUD
Abhishek Gupta
6/8/20263 min read


Step 2.2: Building the Reasoning Extraction Function
Qwen 3.7 Max returns its logical reasoning trace inside reasoning_content chunks before returning the actual output. We need a clean helper function to extract both components while streaming.
Hands-On Lab: Building Autonomous Code-Optimizing Agents with Qwen 3.7 Max
Artificial Intelligence is transitioning from passive conversational chatbots to autonomous agents capable of independent planning, tool usage, and execution. At the absolute forefront of this shift is Alibaba's flagship model: Qwen 3.7 Max.
Designed from the ground up for the agentic era, Qwen 3.7 Max introduces native Thinking Preservation (preserve_thinking), permitting complex reasoning traces to persist across multiple execution turns.
In this hands-on lab, we will bypass the theory and build a modular, step-by-step Thinking-Preserving Code Optimization Agent.
Lab Architecture Map
Before writing any code, let's look at the flow of our hands-on lab. The diagram below illustrates how your local runner script coordinates with the Qwen 3.7 Max API, managing the transition from planning to code generation and safety verification.
Lab Objectives
By completing this hands-on tutorial, you will:
Configure an asynchronous connection to the Qwen 3.7 Max model.
Build a modular multi-turn execution harness that caches the model's intermediate reasoning trace.
Observe how Qwen leverages "thinking preservation" to optimize code and perform independent self-corrections.
Lab 1: Prerequisites & Environment Setup
In this step, we will configure your developer environment, install dependencies, and authenticate your local script with Alibaba Cloud Model Studio.
Step 1.1: Install Dependencies
Open your terminal and install the official OpenAI SDK. Since Alibaba Cloud Model Studio utilizes an OpenAI-compatible API interface, the standard client works natively:
Step 1.2: Obtain and Bind Your API Key
Log in to your Alibaba Cloud Model Studio Console.
Navigate to API Keys and generate a new key.
Export the key in your terminal session so the lab scripts can query it:
Best Practices for Agentic Engineering
When translating this lab experience into production enterprise systems on Alibaba Cloud, keep these optimization guidelines in mind:
Implement a Token Watchdog: Agent runs can easily spiral out of control if loops hit bugs. Always wrap multi-turn operations in limits that cap the session at a safe number of turns (e.g., maximum 5 or 10 sequential steps).
Leverage System Prompt Separation: Keep user prompts clean and focused on individual tasks. Push high-level behavioral rules (like formatting restrictions or security policies) up to the permanent system role instructions.
Store Caches Strategically: In stateful microservices, serialize the conversation JSON arrays (including reasoning_content) to your session database. This lets your backend reconstruct the precise context state for subsequent user interactions at a later time.
By mapping out tasks into modular labs, you can build production-ready software agents that leverage Qwen 3.7 Max's reasoning capabilities. Through native thinking preservation, your applications can transition from simple prompt-response interactions into self-improving, autonomous loops that write, debug, and secure complex operations independently verify highly efficient logic.
Lab 2: Creating the Modular Runner (agent_runner.py)
Rather than maintaining a giant, complex program, we will write our script in bite-sized, logical components. Create a new file named agent_runner.py and implement the following sections step-by-step.
Step 2.1: Imports and Client Initialization
Add the required packages and configure the unified DashScope API gateway.
Lab 3: Executing the Multi-Turn Code Optimization Workflow
Now, let's assemble the steps to run our multi-turn optimization workflow. We will feed a slow, unoptimized Python matrix operation to the agent and watch it plan, optimize, and perform a self-correction.
Add this orchestrator code at the bottom of your agent_runner.py file:
Lab 4: Running and Verifying Your Agent
Now it's time to run your workspace script.
Step 4.1: Run the Lab
In your terminal, execute the script:
Step 4.2: Expected Observations
When you review your terminal output, look closely for these behaviors that highlight Qwen 3.7 Max's native agentic design:
Integrated Thought Trace: At the beginning of each phase, you will see a rapid stream of text inside [Thinking Trace]. This is the model analyzing the code before outputting the actual implementation.
Context Persistence: In Phase 2, notice how the model references details it planned during Phase 1. By feeding "reasoning_content" back in the conversation array, Qwen did not need to re-evaluate the code from scratch. It built directly upon its previous analytical thoughts.
Automated Self-Correction: In Phase 3, when prompted with edge-case validation, watch how the model reviews its implementation from Step 2, checks if it omitted shape matching or safety checks, and dynamically adds those safeguards.
Conceptual Visualization: Thinking-Preserved Memory Flow
To understand why this method prevents the context drift common in standard LLM systems, observe how the conversational states are linked together in the context window:
