LLM vs Code: When Should an Agent Use Each?
In this article
When an AI agent faces a task, it should use code for deterministic, repeatable operations and an LLM for judgment, interpretation, and generation. The rule of thumb: if the answer is verifiable and the steps are fixed, use code; if the answer is open-ended or requires understanding, use an LLM.
Background: Why the Question Exists
Modern AI agents—like those powering customer support bots, research assistants, and automation tools—can call both large language models and traditional code. LLMs excel at understanding natural language, summarizing, and generating text, but they can also hallucinate facts and struggle with exact arithmetic. Code, on the other hand, is precise and deterministic but cannot understand nuance. Early agent frameworks often defaulted to LLM for everything, leading to errors like calculating 2+2 as 5 or inventing a nonexistent API. The challenge is knowing when to use which.
How Agents Use Tools
An agent typically receives a user request, decides which tool to call, and then uses the result. Tools can be code functions (e.g., a calculator, a database query, a web API call) or LLM prompts. The agent's decision-making can be:
- Rule-based: The developer writes conditions like "if the user asks for a sum, call the calculator."
- LLM-based: The agent's LLM selects a tool based on the user's phrasing, then passes the output to another tool if needed.
In practice, a hybrid approach works best: the LLM interprets the user's intent, and code handles the actual computation or data retrieval.
When to Use Code
Code is the right choice when the task is well-defined and the output must be exact. Examples include:
- Arithmetic, unit conversions, or any calculation where a wrong answer is unacceptable.
- Data processing: filtering, sorting, aggregating, or transforming structured data.
- API calls where the request and response are strictly formatted.
- String manipulation like regex matching or formatting dates.
- Any operation where the same input should always produce the same output.
For instance, if a user asks "What's the square root of 144?", an LLM might say "12" but could also say "12.0" or occasionally "12.1". Code returns exactly 12.0 every time.
When to Use an LLM
LLMs shine in tasks that require language understanding, generation, or judgment. Use an LLM when:
- Summarizing a long document or extracting key points.
- Answering open-ended questions like "Explain the concept of gravity."
- Generating creative content: emails, stories, or marketing copy.
- Understanding user intent from messy or ambiguous input.
- Classifying text into categories that aren't strictly defined.
For example, a customer support agent might use an LLM to interpret a frustrated email and draft a polite response, but use code to look up the customer's order status.
How to Choose: A Decision Framework
Here is a practical guide to decide:
- Is the task deterministic? If yes, use code. If no, go to step 2.
- Does it require factual accuracy? If yes, use code (or a database) and verify with an LLM only if needed.
- Does it require understanding or generation? If yes, use an LLM.
- Is there a risk of hallucination? If yes, avoid LLM for the core answer; use it only to interpret.
In complex tasks, combine both: use an LLM to parse the user's request, extract parameters, then call code to compute, and finally use an LLM to format the response.
Common Pitfalls and Misconceptions
A common mistake is assuming LLMs can do math reliably. They cannot—they are language models, not calculators. Even with large numbers, they may approximate. Another pitfall is using code for tasks that need nuance, like sentiment analysis, where code would fail. Also, agents that rely solely on LLMs for tool selection can get stuck in loops or pick the wrong tool. A hybrid approach with clear fallbacks is safer.
Cost and Performance Trade-offs
LLM calls are slower and more expensive than code execution. Each API call has a cost and latency, while code runs in milliseconds. For high-volume tasks, minimizing LLM calls is crucial. For example, a web scraper that uses an LLM to parse every page would be impractically slow; instead, use regex or a parser for the structure, and only invoke an LLM for anomalies.
Safety and Reliability
Code is reliable but can crash if inputs are unexpected. LLMs can produce unsafe or biased outputs. When safety matters, always validate LLM outputs with code. For instance, if an LLM generates a SQL query, run it through a validator before executing. Never let an LLM directly execute code without sandboxing, as it might produce malicious commands.
Frequently Asked Questions
Can an LLM write code to solve the problem?
Yes, an LLM can generate code, but that code must be executed by a runtime. The LLM is not the executor; it's the programmer. For example, an agent might ask an LLM to write a Python script to sort a list, then run that script. This is often the best of both worlds.
What if the LLM gives a wrong answer?
If the task is deterministic, use code. If you must use an LLM, add a verification step: ask the LLM to explain its reasoning, or cross-check with a code-based tool. For factual queries, use a retrieval system rather than relying on the model's memory.
Should I always use code for calculations?
Yes, for any calculation where precision matters. LLMs are not designed for arithmetic. Even simple percentages can be wrong. Use a calculator tool or a code function.
How do agents decide which to use?
Most agents use a combination: a router (often an LLM) classifies the request and sends it to the appropriate tool. Some frameworks allow the LLM to output a JSON that specifies the tool and parameters, which is then executed.
Is it ever okay to use an LLM for math?
Only for approximate estimates or when the user doesn't need exact numbers. For instance, "roughly how many calories in a pizza?" might be fine, but "what is 17% of 2300?" should be code.