LLM Code Execution: From Text-Based Reasoning to Agentic Vision
This article explains how code execution extends large language models beyond text generation by externalizing reasoning into runnable programs. It covers how the capability works, its typical use in precise calculation and text processing, and its application to agentic vision, where models crop, annotate, and re-examine images. It also outlines the security and isolation requirements, practical engineering recommendations, and the trend toward implicit, built-in code execution.
1. Why LLMs Need Code Execution
Large language models excel at language modeling and pattern transfer, but their weaknesses are equally clear: unstable arithmetic precision, drift during multi-step derivations, and no reliable way to measure tables and images precisely. When a task escalates from “write a paragraph” to “solve an equation, compute statistics, or verify a geometric relationship,” a single forward pass of generated text often produces conclusions that look plausible but cannot be verified.
Code execution is introduced into the model system as a tool capability. The core idea is to externalize reasoning into a runnable program: the model first generates Python code, then runs it in a controlled environment, reads the standard output, variable results, or charts, and iteratively refines its approach until it converges on a final answer. This pipeline replaces probabilistic guessing with deterministic computation and, for the first time, makes the model’s intermediate steps auditable.
It is worth emphasizing that code execution is not simply about teaching the model to “program.” It equips the reasoning process with an external verifier. Any problem that can be formalized as a computation can be handed to the interpreter for a unique answer, while the model is responsible only for modeling, invoking the tool, and interpreting the result.
2. Capability Boundaries and How It Works
From an engineering perspective, this capability typically has the following characteristics:
- On the input side, it accepts both plain text and multimodal content, allowing images and tables to be treated as analysis targets.
- On the output side, the result may be a final text conclusion, a code snippet, or a visualization.
- Execution takes place in an isolated sandbox provided by the service and completes parsing and running within a single request.
- The model can read execution results across multiple turns, forming a “generate-execute-observe-refine” loop.
To enable it, you generally declare the available tools when constructing the model instance. The following is illustrative code (pseudocode that only expresses the call structure):
model = GenerativeModel(model_name="...", # The specific model is provided by the platformtools=[CodeExecution()] # Declare the code execution tool)response = model.generate_content("Solve the system of equations and explain the steps: 2x + y = 7, x - y = 2")print(response.text)
What matters in this code is not the syntax but the structure: the tool is declared as a capability, the model autonomously decides whether to call it during reasoning, and the call result flows back into the context to continue reasoning.
3. Use Case 1: Precise Calculation and Text Processing
In scenarios such as solving equations, numerical statistics, unit conversion, and date arithmetic, a common language model failure is “right process, wrong result.” With code execution, the model translates constraints into symbolic operations or numerical iteration, lets the interpreter produce the result, and then expresses it in natural language.
Example:
# Code the model might generatefrom sympy import symbols, solvex, y = symbols('x y')sol = solve([2*x + y - 7, x - y - 2], [x, y])print(sol) # Outputs the unique solution for the model to compose the final answer
The same applies to text processing: token counting, regex extraction, format conversion, and batch replacement can all be handed to code, avoiding the model “counting by feel” over long text.
4. Use Case 2: Agentic Vision
This is the most imaginative direction for code execution. Traditional visual understanding is “take a look and give an answer,” whereas agentic vision turns the model into an active operator: it generates code to crop, zoom, and annotate image regions, then makes a second-pass judgment on the local area, upgrading passive recognition into active evidence gathering.
A typical workflow includes:
- Scan the input image as a whole and propose hypotheses to verify.
- Generate code to crop regions of interest (such as building outline edges or dense table areas).
- Draw bounding boxes and numeric labels on the canvas to fix the evidence in place.
- Refine the conclusion based on local results, repeating the steps above when necessary.
Example:
from PIL import Image, ImageDrawimg = Image.open("input.png")crop = img.crop((120, 80, 420, 380)) # Crop the region to verifycrop.save("region.png")draw = ImageDraw.Draw(img)draw.rectangle((120, 80, 420, 380), outline="red", width=3)draw.text((122, 60), "ROI-1", fill="red")img.save("annotated.png")
In public demonstrations, this approach delivers a notable accuracy improvement in iterative inspection scenarios involving high-resolution images and can parse dense tables into verifiable drawing results. Its engineering value lies in the fact that conclusions come with a chain of evidence, making manual review easier.
5. Security and Isolation: A Prerequisite That Cannot Be Skipped
Code execution means running model-generated code, so the risks must be designed for up front:
- Sandbox isolation: a container or micro-virtual machine with a read-only root filesystem and dangerous system calls disabled.
- Resource quotas: limits on CPU, memory, execution time, and output size to prevent infinite loops and amplification attacks.
- Network policy: outbound network access disabled by default and opened only in a controlled manner via a whitelist.
- Dependency governance: pre-installed, fixed-version dependencies to avoid arbitrary installation at runtime.
- Input validation: strict checks on file paths, dimensions, and encoding to guard against path traversal and parsing vulnerabilities.
- Audit trail: logging of generated code, execution logs, and artifacts for traceability.
6. Engineering Recommendations
- Define the applicable boundaries: hand formalizable computation to code and leave semantic judgment to the model.
- Control the number of iterations: set a maximum number of refinements and a confidence threshold to avoid infinite loops.
- Structure the results: have code output structured formats such as JSON to reduce the model’s secondary misreading.
- Observability: integrate logging services and monitoring alerts, with thresholds for failure rate, latency, and resource usage.
- Combine with general cloud capabilities: use object storage for artifacts, message queues for peak shaving, container platforms to host the sandbox, and a key management service to manage credentials.
7. Evolution Trends
Based on public information, this capability is moving from “explicit tool calls” toward “implicit embedding”: users no longer need to be aware of the code, as the model automatically decides when to compute, when to draw, and when to double-check. At the same time, coverage is expanding from a single lightweight model to more model sizes. The takeaway for developers is to treat “verifiability” as a first-class citizen in application design rather than an afterthought patch.
8. Conclusion
The essence of code execution is to equip large language models with an external verifier: making computation reproducible, giving visual judgments evidence, and making outputs auditable. With the trio of isolation, quotas, and auditing in place, it can significantly improve the reliability of complex tasks. Agentic vision, meanwhile, signals that models are moving from “describing the world” to “operating on the world and self-verifying.”
