AI Art Without Image Models: A Practical Guide to Code-Driven Painting with LLMs
Explore how large language models can drive a Python painting engine to create AI art through code-generated brush strokes, without relying on diffusion models. This guide covers the core principles, engine architecture, data structures, iterative feedback loop, engineering challenges, and cloud deployment strategies for building controllable, reproducible, and interpretable programmatic painting systems.
1. Introduction: Two Technical Paths in AI Painting
Almost every mainstream AI painting solution today relies on diffusion models. The core logic works like this: given a text prompt, the model starts from random noise and progressively denoises it over multiple steps to reconstruct an image that matches the description. The advantage is high efficiency and stable generation quality. The drawback is equally clear—the generation process is a “black box.” Developers can hardly control the direction of each individual stroke, nor can they intervene or make corrections at intermediate stages.
However, a fundamentally different approach has recently been drawing attention: instead of invoking any image generation model, it lets a large language model (LLM) directly write Python code that simulates the physical properties of a real brush and paints stroke by stroke on a virtual canvas. This approach transforms the creative process from “end-to-end pixel generation” into a “readable, controllable, and correctable sequence of programmatic brush strokes,” opening up new possibilities for AI art.
2. Core Principles: From “Generating Pixels” to “Orchestrating Strokes”
2.1 How Traditional Diffusion Models Work
The painting process of a diffusion model can be summarized as follows:
- Gradually add noise to training images and learn the inverse process from noise back to the image.
- During generation, start from pure random noise and iteratively reconstruct the image along the learned denoising path.
- Each denoising step is guided by the text prompt through a cross-attention mechanism.
The final image the user sees is the result of hundreds or even thousands of denoising iterations. While efficient, this process has three inherent problems:
- Lack of control: Users cannot specify “which position the third stroke should land on” or “how wide the brush should be for this line.”
- Lack of interpretability: When generation fails, it is difficult to pinpoint which stage went wrong.
- Style homogenization: Because the model learns the distribution of training data, generated results tend to converge toward mainstream styles.
2.2 How Code-Driven Painting Works
The core idea of code-driven painting is: let the model break down “painting” into “writing code that operates a brush.” Specifically:
- The LLM understands the creative intent (e.g., “paint a bird at sunrise”).
- The model decomposes the creative intent into a series of stroke instructions, each containing parameters such as coordinates, brush type, color, width, and opacity.
- A painting engine (usually a Python library) interprets these instructions and actually renders the corresponding strokes on the canvas.
- The model can observe the rendered result, identify deviations, and write new strokes to make corrections.
This approach turns the painting process into an observable, debuggable, and iterative programming task. Instead of outputting an image in a single pass, the model behaves like a painter: observing the canvas, thinking about the next move, laying down a stroke, and observing again.
3. Key Implementation Details
3.1 Data Structure for Stroke Instructions
Each stroke instruction needs to carry rich parameters. Below is an illustrative data structure:
@dataclassclass BrushStroke:color: str # Hex color code, e.g., "#30346a"width: int # Brush width (in pixels)opacity: float # Opacity, simulating paint concentrationpath_points: list # List of path control pointsbrush_type: str # Brush type: flat, round, fan, dry, etc.jitter: float # Path jitter amplitude, simulating hand-drawn imperfectionwetness: float # Paint wetness, affecting edge diffusion
Several key parameters deserve attention in their design logic:
- Jitter amplitude (
jitter): Human muscle movements have tiny irregularities, so perfectly straight lines actually look unnatural. Experiments show that adding a random offset of about 3–7 pixels to path points significantly improves the natural feel of a stroke. - Paint wetness (
wetness): Wet paint produces capillary diffusion on canvas fibers, creating soft, feathered edges. Dry paint leaves sharp edges, suitable for fine detail work. - Brush type (
brush_type): Different brush types determine the basic shape of a stroke. Fan brushes are suited for large-area base coloring, round brushes for outlining contours, and dry brushes for simulating rough texture effects.
3.2 Painting Engine Architecture
A basic painting engine needs to include the following modules:
class PaintingEngine:def __init__(self, canvas_width, canvas_height):self.canvas = Image.new("RGB", (canvas_width, canvas_height), "white")self.stroke_history = []def apply_stroke(self, stroke: BrushStroke):"""Render a stroke on the canvas"""# 1. Generate actual path points based on jitter parameteractual_points = self._apply_jitter(stroke.path_points, stroke.jitter)# 2. Compute stroke shape based on brush type and wetnessbrush_mask = self._compute_brush_mask(stroke.brush_type,stroke.width,stroke.wetness)# 3. Draw along the path with paint effectsself._render_along_path(actual_points, brush_mask, stroke.color, stroke.opacity)# 4. Record stroke history for backtracking or modificationself.stroke_history.append(stroke)def get_current_state(self):"""Return current canvas state for model observation and decision-making"""return self.canvas
3.3 The Iterative Correction Mechanism
A key advantage of code-driven painting is support for intermediate feedback. The working loop is as follows:
- Initialization: The model generates the first batch of strokes (typically background fill or large outlines).
- Observation: Retrieve the rendered result of the current canvas (either as an image or as statistical features of the canvas).
- Diagnosis: The model analyzes the canvas state and identifies deviations (e.g., “the bird’s back lines are too thin” or “the color tone is too cool”).
- Correction: Write new stroke instructions to overwrite or supplement the affected areas.
- Repeat: Until the model judges the work is complete or the stroke count limit is reached.
It is worth noting that the constraint strokes cannot be undone once applied is closer to the physical limitations of real painting and forces the model to “think clearly before painting.” This contrasts interestingly with the diffusion model’s “one-shot generation with no intervention”—while code-driven painting is controllable per stroke, once a stroke is applied it becomes permanent, adding to the planning difficulty.
4. Breakdown of a Real-World Case
An engineering team once ran an experiment: asking a model to paint “a bird at sunrise” using only code to simulate the physical properties of a brush. The final piece used 111 strokes and completed in about 21 seconds.
The instruction for the first stroke was:
# Stroke 1: sky base colorstroke_001 = BrushStroke(color="#30346a", # Deep blue, simulating the pre-dawn skywidth=90, # Wide brush for fast base coverageopacity=0.7, # Semi-transparent, leaving room for later layeringpath_points=[(0, 0), (200, 5), (400, 3), (600, 8), (800, 0)],brush_type="round", # Round brush for soft transitionsjitter=5, # ~5px jitter to avoid a mechanical feelwetness=0.6 # Medium wetness, slightly diffused edges)
The model’s reasoning when planning this stroke was: “The pre-sunrise sky shows a deep blue gradient. The first stroke needs to quickly cover the upper canvas with a wide brush for efficiency, while staying semi-transparent to allow warm-color overlays later.”
When the model observed that the bird’s back area had overly thin lines and a loose structure, it appended a correction stroke:
# Correction stroke: strengthen the bird's back contourstroke_058 = BrushStroke(color="#1a1a2e",width=15,opacity=0.9,path_points=[(320, 180), (340, 175), (360, 178)],brush_type="fine_round",jitter=2,wetness=0.3)
This “observe–correct” loop allows the model to progressively refine details through repeated review of the work, much like a human painter.
5. Unique Advantages of Code-Driven Painting
5.1 Full Controllability and Reproducibility
Unlike diffusion models, every stroke in code-driven painting is an explicit instruction. This means:
- Precise control: Developers can specify “stroke 37 has a brush width of 12 pixels and color #8B4513.”
- Full reproducibility: The same code always produces the same image, with no uncertainty from random seeds.
- Mid-process intervention: New instructions can be inserted after any stroke to redirect the subsequent creation.
5.2 Stroke-Level Interpretability
When a problem occurs in the artwork, the code-driven approach lets developers directly inspect the stroke history:
# List all stroke recordsfor i, stroke in enumerate(engine.stroke_history):print(f"Stroke {i}: color={stroke.color}, width={stroke.width}, "f"type={stroke.brush_type}, path_points={len(stroke.path_points)}")
This interpretability is especially valuable for art education and creative assistance tools—learners can analyze the creation process of a piece stroke by stroke and understand the causal relationship between strokes and visual effects.
5.3 Personalized and Distinctive Styles
Because the model must plan its own stroke strategy, different models may develop radically different “painting habits.” For example:
- Some models prefer to fill the background with large brushes first, then progressively refine details.
- Some models favor starting from a local area and building region by region.
- Some models deliberately introduce irregular jitter, pursuing a “freehand” or expressive style.
This variation makes code-driven painting more likely to produce distinctive personal styles, rather than converging toward the statistical average of training data.
6. Engineering Challenges and Mitigation Strategies
6.1 The Stroke Count Explosion Problem
Drawing a detailed work may require thousands or even hundreds of thousands of strokes. If the model needs to generate detailed instruction code for each stroke, context length becomes a bottleneck.
Mitigation strategies:
- Hierarchical planning: First generate a high-level stroke strategy (e.g., “fill the sky first, then draw the bird body, finally add details”), then refine specific instructions within each level.
- Parameterized strokes: Define reusable stroke patterns (e.g., “gradient fill,” “outline tracing”) to reduce repetitive instruction descriptions.
- Batch processing: Merge strokes with similar attributes into a single code call.
6.2 Computational Cost of Visual Feedback
The model needs to “see” the current canvas state to make correct correction decisions. Converting a high-resolution canvas into input the model can understand involves image encoding overhead.
Mitigation strategies:
- Downsampled feedback: Downsample the canvas to a low-resolution thumbnail for the model to observe; use full resolution only when fine-grained judgment is needed.
- Feature-based feedback: Extract key statistical features of the canvas (e.g., color distribution, edge density, regional contrast) and provide them to the model as structured data.
- Incremental rendering: Render only the most recently added strokes and their affected regions, avoiding full-canvas redraws.
6.3 Physical Realism of Strokes
To make digital painting look “like real painting,” the physical behavior of paint must be simulated, including:
- Paint mixing: When different colors overlap, they should produce effects consistent with color mixing rules (e.g., transparent layering in watercolor, opaque covering in oil paint).
- Canvas texture: The texture of canvas fibers affects how paint adheres and spreads.
- Brush wear: Real brushes wear down during use, causing stroke shapes to gradually change.
Mitigation strategy: At the implementation level, physics-based rendering methods can be used, such as modeling paint as a fluid or particle system and performing parallel computation on the GPU.
7. Cloud Architecture Considerations for Productization
For teams looking to productize code-driven painting capabilities, consider the following cloud architecture:
- Model inference layer: The LLM handles stroke planning and code generation; it can be deployed on a container platform for elastic scaling.
- Painting engine layer: The Python painting engine handles code execution and canvas rendering; GPU acceleration can be used for latency-sensitive scenarios.
- State management layer: Stroke history and canvas state require persistent storage; object storage can hold intermediate artifacts to support resume-from-checkpoint painting.
- Task scheduling layer: Large-scale batch creation tasks can be asynchronously scheduled via message queues to avoid blocking user requests.
- Quality monitoring layer: Use logging and alerting services to track metrics such as generation success rate, stroke count distribution, and average completion time.
8. Future Outlook
Code-driven painting represents a noteworthy technical direction: it shifts AI creation from “generation” to “orchestration,” and from “black-box output” to “white-box construction.” While it currently cannot yet match traditional image generation models in efficiency and fine detail, its unique controllability, interpretability, and style diversity give it irreplaceable value in scenarios such as education, artistic creation assistance, and programmatic content generation.
As LLM reasoning capabilities improve and painting engine performance is optimized, this “painting with code” paradigm is expected to land in more areas—from helping artists explore creative ideas, to producing programmatic art assets for games and animation, to enabling developers to understand and participate in artistic creation through a programming mindset.
