Introduction
Production LLM applications are evolving beyond single-prompt interactions toward autonomous agents that plan, remember, and act. While a standard LLM application follows a linear "input-process-output" flow, an agentic system implements a loop: it observes its environment, reasons about the current state, takes an action via a tool, and then observes the result of that action to inform its next step.
Agent architectures combine large language models with planning logic, memory systems, and tool integration to handle complex, multi-step workflows that a single model invocation cannot reliably complete. For example, while a standard LLM can write a SQL query, an agent can analyze a database schema, write the query, execute it, analyze the results, realize it missed a join, rewrite the query, and finally provide a synthesized answer to the user.
This post covers practical patterns for building production-grade LLM agents, organized around the three core pillars of agency: planning, memory, and tool use.
Planning Patterns
Planning is the agent's ability to break down a high-level user request into a sequence of manageable steps, decide which steps to execute, and adapt those steps based on real-time feedback. Without a planning layer, an agent is merely a stateless function caller prone to compounding errors.
1. Zero-Shot Planning
In zero-shot planning, the model generates a plan directly from the user prompt without prior examples. This is the simplest form of planning and relies entirely on the model's internal reasoning capabilities.
def zero_shot_plan(user_request: str) -> list[str]:
prompt = f\"\"\"You are an expert agent planner. Break down the following user request into a
sequence of logical, independent steps.
Request: {user_request}
Return only the list of steps, one per line, without numbering.\"\"\"
response = model.generate(prompt)
return [line.strip() for line in response.split(\"\\n\") if line.strip()]
Best for: Simple, well-defined tasks where the path to the solution is linear and predictable. Limitations: It lacks a feedback loop. If the model makes a mistake in step 2, it will blindly proceed to step 3 based on the failed outcome of step 2.
2. Few-Shot Planning
Few-shot planning provides the model with a set of "golden" request-plan pairs. This anchors the model's output to a specific format and quality bar, reducing the variance in how it decomposes tasks.
| User Request | Example Plan |
|---|---|
| "Find the top 5 customers by revenue and email them" | 1. Query customer database for total revenue per user. 2. Sort results in descending order. 3. Slice the top 5 records. 4. Retrieve contact emails for those 5 users. 5. Draft personalized emails based on their purchase history. 6. Send emails via SMTP tool. |
Best for: Complex tasks that require a specific architectural approach or strict adherence to a business process. Trade-off: Increases the input token count and requires a maintained library of high-quality examples.
3. Structured Reasoning (ReAct and Chain-of-Thought)
The most powerful planning pattern for production agents is the ReAct (Reason + Act) loop. Unlike linear planning, ReAct interleaves reasoning traces with actions. The agent does not commit to a full plan upfront; instead, it reasons about the current state, takes one action, observes the result, and then reasons again.
The ReAct Cycle:
- Thought: The agent explains what it is thinking and why it needs a specific piece of information.
- Action: The agent calls a tool (e.g.,
search_database). - Observation: The tool returns a real-world result (e.g., a JSON object from an API).
- Repeat: The agent uses the observation to update its "Thought" and decide the next "Action."
Thought: The user wants to know the current price of NVDA stock. I need to use the finance tool.
Action: get_stock_price(symbol=\"NVDA\")
Observation: {\"symbol\": \"NVDA\", \"price\": 125.40, \"currency\": \"USD\"}
Thought: I have the price. Now I should check the 24-hour change to provide a complete answer.
Action: get_stock_history(symbol=\"NVDA\", period=\"24h\")
Observation: {\"start_price\": 120.10, \"end_price\": 125.40}
Thought: The price increased by about 4%. I can now answer the user.
Final Answer: NVDA is currently trading at $125.40, up 4% over the last 24 hours.
Memory Systems
Memory allows agents to maintain state across multiple turns and separate sessions. In production, a single context window is insufficient; you need a tiered memory architecture that balances precision with cost.
1. Working Memory (Short-Term)
Working memory is the active context window of the current session. Because token limits are finite, you must implement a management strategy:
- Sliding Window: Keeps the last $N$ messages. Simple to implement but loses the beginning of the conversation.
- Priority Retention: Uses an LLM or heuristic to identify "critical" messages (e.g., user's name, specific preferences, goal statements) and pins them to the top of the context regardless of age.
- Recursive Summarization: As the conversation grows, the agent periodically summarizes the older turns into a concise "state of the union" block, freeing up tokens for new interactions.
2. Episodic Memory (Long-Term Experience)
Episodic memory stores specific past interactions—what the agent did, how the user reacted, and whether the outcome was successful. This allows the agent to "learn" from its own history.
Implementation Pattern: Store every completed task as a "trajectory" in a vector database. Each entry includes:
- Input: The original user request.
- Steps: The sequence of thoughts and actions taken.
- Outcome: A success/failure label and user feedback.
When a new request arrives, the agent performs a similarity search over its episodic memory to find a similar past task. It then injects that trajectory as a few-shot example: "Last time I handled a similar request for a revenue report, I found that querying the 'orders' table first was more efficient than the 'customers' table."
3. Semantic Memory (Knowledge Base)
Semantic memory is a repository of factual knowledge (documentation, product specs, company policies) that is independent of any specific user. This is typically implemented as a RAG (Retrieval-Augmented Generation) system.
Production Tip: Use Metadata Filtering in your semantic memory. Instead of a raw vector search, allow the agent to specify filters (e.g., filter={\"product_version\": \"v2.0\"}) to ensure it doesn't retrieve outdated documentation.
Tool Use Patterns
Tools are the "hands" of the agent. The gap between a "chatbot" and an "agent" is the ability to execute side effects in the real world.
1. The Tool Definition Layer
To enable reliable tool use, tools must be defined with strict, machine-readable schemas (typically JSON Schema). The model needs to know exactly what types are expected.
{
\"name\": \"get_customer_revenue\",
\"description\": \"Retrieves total lifetime revenue for a specific customer ID\",
\"parameters\": {
\"type\": \"object\",
\"properties\": {
\"customer_id\": { \"type\": \"string\", \"description\": \"The UUID of the customer\" }
},
\"required\": [\"customer_id\"]
}
}
2. Security and Sandboxing
Executing model-generated tool calls in production is dangerous. Implement these four layers of defense:
- Input Validation: Never pass raw model output directly into a database query. Use parameterized queries or Pydantic models to validate types.
- The "Sandbox" Pattern: For tools that execute code (e.g., a Python interpreter for data analysis), run the code in an isolated container (gVisor or Firecracker) with no network access and a strict timeout.
- Privilege Least-Access: The API key used by the agent should have the minimum permissions necessary. An agent should have
read-onlyaccess to the database unless specifically tasked with an update. - Human-in-the-Loop (HITL): For "high-stakes" tools (sending an email, deleting a file, transferring money), the agent must produce a "Proposed Action" which is then sent to a human for a binary
Approve/Rejectdecision.
3. Tool Selection and Routing
As your agent grows, it may have dozens of tools. Putting all tool definitions into every prompt consumes tokens and confuses the model. Use a Two-Stage Tool Router:
- Classifier: A small, fast model (e.g., Haiku) looks at the query and selects the top 3-5 most relevant tools from the library.
- Executor: The primary reasoning model (e.g., Sonnet) receives only those 5 tool definitions and decides exactly how to use them.
Putting It Together: The Production Agent Loop
A robust production agent loop isn't a simple while loop; it is a state machine.
- Ingestion: Receive request $\rightarrow$ Sanitize input $\rightarrow$ Assign Request ID.
- Context Assembly: Retrieve semantic memory $\rightarrow$ Retrieve episodic memory $\rightarrow$ Load working memory.
- Planning Phase: Use ReAct loop to generate a
Thought$\rightarrow$ select anAction. - Execution Phase: Validate action $\rightarrow$ Check HITL requirement $\rightarrow$ Execute tool $\rightarrow$ Capture
Observation. - Evaluation Phase: Does the
Observationanswer the user's goal?- If YES: Generate final response $\rightarrow$ Save trajectory to episodic memory.
- If NO: Loop back to Planning Phase with the new observation.
- Safety Gate: Pass the final response through a safety filter before delivering to the user.
Error Handling and Recovery
Agentic systems fail in complex ways. You must implement specific recovery patterns:
- The "Stuck" Loop: If an agent calls the same tool with the same arguments three times, it is in a loop. Force a "Reasoning Reset" where the agent is told: "You have tried this action multiple times without success. Please try a different approach or ask the user for clarification."
- Tool Timeout: When a tool hangs, don't let the agent wait forever. Implement a strict timeout and return a standardized error:
Error: Tool [Name] timed out after 10s. This allows the agent to reason about the failure and try a fallback. - Malformed Output: If the model generates a tool call that fails JSON parsing, don't crash. Feed the error back to the model: "Your last tool call was malformed JSON. Please correct the syntax and try again."
Conclusion
Building production LLM agents is a shift from "prompt engineering" to "system engineering." The reliability of an agent depends less on the perfection of the prompt and more on the robustness of the planning loop, the quality of the memory retrieval, and the security of the tool integration.
By treating planning as an iterative process, memory as a tiered architecture, and tools as privileged operations, you can move from fragile prototypes to resilient agents that provide genuine utility in production environments.