Code Execution is a pattern that lets an LLM write and run code in a sandboxed environment during inference. Instead of reasoning about computations in natural language, the model generates executable code, runs it, and incorporates the output into its response.
At a Glance
- Problem: Text generation cannot reliably compute compound interest, multiply large matrices, run SQL against a real database, or render a chart. The model understands what needs to happen but returns plausible guesses or verbal descriptions instead of results.
- Forces: Open-ended computation versus the risk of running code nobody reviewed; precise results versus the latency of spinning up a sandbox; the flexibility of a full language runtime versus the larger attack surface and operating burden it brings.
- Solution: The model writes code in a target language such as Python or SQL, a sandbox with filesystem, network, CPU, and memory limits executes it, and the output returns to the model for its response.
- Consequences: Gains: computational precision, real artifacts such as images, files, and query results, and a full language ecosystem. Costs: a sandbox service to run and patch, added latency, a new attack surface, and code that can run yet return quietly wrong results.
What problem does Code Execution solve?
Language models are good at producing text. They summarize, translate, and reason through problems fluently. But for a wide category of tasks, text alone is not enough. Ask an LLM to compute compound interest over 30 years with monthly contributions and you will get an answer that looks plausible but may be subtly wrong. Ask it to generate a bar chart and it will describe one in words rather than produce an actual image.
The gap shows up across many kinds of work. Data analysis requires running real computations against real datasets. Visualization demands executable rendering code, not a verbal description of what a chart should look like. SQL queries need to hit an actual database to return results. Mathematical proofs benefit from symbolic computation that verifies each step. The LLM understands what needs to happen but lacks the ability to make it happen directly.
You cannot prompt your way around this limit. No amount of chain-of-thought reasoning will make an LLM reliably multiply large matrices or render a Matplotlib figure; that takes real code running on real hardware.
How does Code Execution work?
The Code Execution pattern splits the work into two distinct phases. First, the LLM generates code that solves the problem. Second, a sandboxed runtime executes that code and returns the results. The LLM plays the programmer and the sandbox plays the computer.
In effect, the model gets a scratch pad that runs. When a user asks "show me a scatter plot of revenue vs. headcount for these 50 companies," the LLM writes a Python script using Matplotlib or Plotly, the sandbox executes it, and the rendered image comes back to the user. The model never tries to draw the chart itself. It writes the instructions and lets a real interpreter do the work.
Do not skip the sandbox. LLM-generated code is code you did not write and did not review, and the sandbox constrains what it can do: no filesystem access beyond a temporary working directory, no network calls unless explicitly allowed, and limits on CPU time and memory. Running untrusted code without isolation will eventually cause a security incident.
This pattern works with many target languages. Python is the most common because of its ecosystem for data science and visualization. SQL is another natural fit, where the LLM writes a query and the sandbox executes it against a database connection. Graphviz DOT notation lets the model describe graph structures that get rendered into diagrams. The LLM does not need to understand rendering pipelines or database internals. It only needs to produce syntactically correct code in the target language.
When should you use Code Execution?
Use Code Execution when the task involves computation, data transformation, or artifact generation that an LLM cannot reliably do through text generation alone.
Specific signals that this pattern fits well:
- The user needs a chart, graph, or visualization as output
- The task involves numerical computation where precision matters (financial calculations, statistics, simulations)
- You need to query structured data in a database
- The output is a file (PDF report, CSV export, image) rather than plain text
- The problem involves iterative data manipulation, things like filtering, grouping, pivoting, and aggregating a dataset
If the task is purely about generating or transforming text, you probably do not need this. If the task requires interacting with external APIs or services, tool calling might be a better fit. Code Execution fits when the LLM needs a programming language runtime to produce results it cannot produce through token generation.
When not to use it: when the computation is trivial, such as a single percentage or date difference, a Tool Calling request to a calculator is faster and cheaper than spinning up a sandbox. Avoid it when you cannot run generated code in an isolated environment with resource limits and no open network access, because the attack surface is the main risk. In latency-sensitive chat flows without warm sandbox pools, the extra round trip can make the product feel sluggish.
Worked Example: Cost and Latency
An analytics assistant answers 1,000 questions a day about a 2,000-row sales table on the large model.
| Setup | Calls per request | Tokens per request (in / out) | Cost per 1,000 requests | Latency per request |
|---|---|---|---|---|
| No pattern: table pasted into the prompt, computed in text | 1 | 40,000 / 800 | $132.00 | 13.8 s |
| Code Execution | 2 | 1,700 / 550 | $13.35 | 12.2 s |
| Code Execution with one failed run and a retry | 3 | 3,200 / 850 | $22.35 | 19.7 s |
Assumptions: the full table is about 40,000 tokens and the text-only answer reasons for 800 tokens. With code, the prompt carries the schema and five sample rows (600 tokens), the model writes a 300-token script, the sandbox run takes an assumed 2 s and returns a 200-token result, and the model writes a 250-token answer. A retry adds a 150-token error message, a rewritten 300-token script, and a second 2 s run.
Pasting costs 40,000 × $3.00 per million = $0.12 plus 800 × $15.00 per million = $0.012, so $132.00 per 1,000. Code Execution reads 600 + 1,100 = 1,700 tokens ($0.0051) and writes 550 ($0.00825), so $13.35. Its latency is (0.5 + 300 / 60) + 2 + (0.5 + 250 / 60) ≈ 12.2 s.
The pattern wins once the data is larger than the code that summarizes it, even with a retry; for a one-line calculation the extra call and sandbox time make it slower than answering directly.
What are the common pitfalls?
The most common failure is generated code that does not run because of syntax errors, missing imports, or incorrect API usage. The LLM might reference a library function that does not exist or pass arguments in the wrong order. This is especially common with less popular libraries where the model has seen fewer training examples.
A subtler problem is code that runs but produces wrong results. The LLM might write a SQL query that returns data but applies the wrong join condition, giving you plausible looking numbers that are quietly incorrect. Unlike a runtime error, this failure mode is silent.
Security is the big risk. If your sandbox has gaps, generated code could read sensitive files, make network requests to exfiltrate data, or consume excessive resources. Some teams have learned this the hard way by running LLM-generated code in a standard Docker container without resource limits, only to have a while-true loop consume all available CPU.
Latency adds up as well. Spinning up a sandbox, executing code, and returning results adds time compared to a direct LLM response. For interactive applications, this delay can feel sluggish if you are not careful about sandbox warm-up and pooling.
Over-reliance on code execution for tasks where simpler approaches work is another anti-pattern. If the user asks "what is 15% of 200," generating and executing a Python script is overkill. A tool call to a calculator or even the LLM doing the arithmetic directly would be faster and cheaper.
What are the trade-offs?
You gain computational precision, the ability to produce real artifacts (images, files, query results), and access to the full ecosystem of a programming language.
You pay with added infrastructure complexity (you need a sandbox service), increased latency per interaction, and a new attack surface that requires ongoing security attention.
Code quality varies. The LLM-generated code is not production code. It is throwaway scripting meant to solve an immediate problem. Do not expect clean, well-architected output; the code only has to run correctly for the specific input.
Debugging gets harder. When something goes wrong, you are debugging code you did not write. Good implementations return both the generated code and any error messages to the LLM so it can self-correct, but this means additional API calls and higher costs.
Sandbox maintenance is real work. You need to keep the sandbox environment updated with the right libraries, patch security vulnerabilities, and monitor resource usage. This is operational overhead that scales with usage.
Goes Well With
Tool Calling provides a complementary mechanism for structured interactions with external services. Code Execution handles open-ended computation while tool calling handles well-defined API operations. Many systems use both, letting the agent decide whether to call a predefined tool or write custom code depending on the task.
ReAct Loop creates a natural home for Code Execution as one of the available actions. The agent reasons about what it needs, generates and executes code, observes the output, and decides what to do next. This suits data analysis workflows where each step builds on the previous result.
Multi-Agent Collaboration benefits from having a dedicated code execution agent that other agents can delegate to. A planning agent might break down a data analysis task, and a code execution agent handles the computational steps while other agents handle summarization or presentation.