From Prompt to Production: What Nobody Tells You About Building Real AI Agents
From the publisher’s feed, collected in the ZeroLabs newsroom.
I wrote recently about how working at a five-person startup taught me to think before touching a keyboard. Building an AI agent for our internal ops platform taught me the same lesson but faster, and at a much higher cost per mistake.AI bot imageMost people’s first experience with AI agents follows the same arc.You write a prompt, get a surprisingly coherent answer, and think this could run itself. Then you try to turn it into something real: a system that classifies intent, calls the right tools, handles ambiguous inputs, and doesn’t quietly fail its way through a workflow someone on your team is depending on.Everything changes.The illusion of “just a prompt.”When we started building our internal agent, the first version looked embarrassingly simple. A system prompt, a few function definitions, and some routing logic. It worked in isolation. It fell apart the moment real users touched it.The problem wasn’t the model. The model was fine. The problem was that prompts don’t operate in isolation they operate inside systems, and systems are unforgiving in ways that language models are not.A prompt that produces a reasonable answer in a playground behaves completely differently when it’s the third step in a pipeline, operating on output from a tool call that was slightly malformed, inside a context window carrying three previous turns of ambiguous conversation.That gap between “it works in testing” and “it works on Tuesday afternoon with real data” is where most of the actual engineering lives.The day the agent picked the wrong tool and didn’t blinkEarly on, our agent had two ways to answer numerical questions: a generic database lookup that let the model summarize results, and a set of computed query handlers that used deterministic ORM aggregations for totals and counts.A user asked: “How much do we owe Alex this month?”The agent routed it to the generic lookup. It fetched the raw rows, handed them to the model, and the model summed them confidently, incorrectly. It was mixing up two different amount fields on the payment records.# What was happening inside the generic pipeline:# Model saw: [{ shift_minimum: 150.00, amount: 197.26 }, ...]# Model summed: shift_minimum values instead of amount# Returned: $412.00 (wrong)# What the computed handler did instead:total = Payment.objects.filter( status="pending", assigned_to=engineer_id).aggregate(total=Sum("amount"))["total"]# Returned: $609.26 (correct)No error. No stack trace. Just a wrong number delivered with complete confidence. The agent had selected the wrong tool, the tool had technically succeeded, and the failure was invisible until someone cross-checked it manually.That’s a different class of bug than anything I’d debugged before. The fix wasn’t catching an exception it was making the routing decision unambiguous, so the model couldn’t choose the generic path when a computed answer existed.Orchestration is where the complexity actually livesI thought the hard part would be the model. Prompt quality, output formatting, getting coherent responses.The hard part was everything around it.What started as input → model → output became: intent classification, tool selection, parameter extraction, entity resolution, constraint validation, retry logic, fallback routing, and an ever-growing list of edge cases that each needed their own handling.At some point you look at what you’ve built and realize it resembles a distributed system more than an operator agent. You’re not writing prompts. You’re designing workflows where the model is one component, an important one, but not the only one that can fail.The thing that helped most was a two-layer routing strategy: catch the obvious cases cheaply before ever touching the model.# Keyword pre-router — runs before any LLM call_NAVIGATION_PATTERNS = [ r'\b(go to|open|show me the|navigate to)\b.*\b(dashboard|calendar|invoices)\b']_GENERAL_PATTERNS = [ r'\b(hi|hello|hey|thanks|thank you|bye)\b']def _try_keyword_route(self, query: str) -> AgentResponse | None: if any(re.search(p, query, re.I) for p in _NAVIGATION_PATTERNS): return self._handle_navigation(query) if any(re.search(p, query, re.I) for p in _GENERAL_PATTERNS): return self._handle_general(query) return None # Fall through to LLM routingEvery matched greeting or navigation request saved a model call. Multiplied across hundreds of daily queries, that adds up in both cost and latency.The multi-turn problem: context doesn’t travel for freeManaging context across multi-turn conversations was the messiest part of the build by a wide margin.Here’s what would happen. A user would start a request say, scheduling a new service appointment. The agent would ask a clarifying question. The user would answer. And on the next turn, the model would sometimes re-classify the entire conversation as a new request, losing everything collected so far.# Turn 1 — user starts a requestUser: "Schedule an appointment for Riverside Properties next Tuesday"Agent: "What time should it start?"# Turn 2 - model forgets the contextUser: "9am"Agent: "Sure! What appointment would you like to schedule?" ← 🚩The fix wasn’t to provide more context in the prompt. It was taking the routing decision out of the model’s hands entirely for follow-up turns. When the frontend detected an active collection flow, it bypassed the orchestrator and sent the continuation context directly to the action handler:# views.pyif request_context.get("continuation"): # Skip orchestrator — we already know what we're doing return await action_agent.process_continuation( message=message, action_type=context["continuation"]["actionType"], collected_params=context["continuation"]["collectedParams"] )# Only new requests go through full routingreturn await orchestrator.route(message)The model was still handling parameter extraction from the user’s reply, but it was no longer responsible for remembering what conversation it was in the middle of. That’s a structural problem, not a prompting problem. No amount of “remember the previous context” in a system prompt fixes it reliably.The fix that changed everything: reframe the task, not the modelThere’s a version of prompt engineering that’s essentially superstition adding phrases like “think step by step” or “you are an expert” and hoping for better results. That wasn’t the fix.The real fix was rewriting what we were actually asking the model to do.Our intent classifier was originally framed as: “Given this user message, what action does the user want to take?” It sounded reasonable. In practice, it was too open-ended. The model would classify “what appointments does Alex have this week?” as a scheduling action instead of a lookup, because scheduling and lookup share vocabulary.We rewrote it as a function-calling spec instead giving the model a concrete list of tools with narrow, specific descriptions, and letting it pick rather than classify:# Before: open-ended classificationsystem_prompt = """Classify the user's intent. Options: lookup, schedule, update, navigate, general."""# After: tool-based routing with tight descriptionstools = [ { "name": "get_engineer_schedule", "description": "Look up existing appointments for a specific engineer. Use when user asks WHAT is scheduled, not to create anything new.", }, { "name": "create_appointment", "description": "Schedule a new service appointment. Use ONLY when user explicitly wants to create something new.", }]Misclassification dropped immediately. Not because the model got smarter, but because we stopped asking it vague questions and started giving it a precise decision to make.Failure is the default, not the exceptionIn traditional software, a failure means something went wrong. In an AI system, failure is the baseline you’re designing away from.The agent picks the wrong tool. It extracts a parameter from the wrong part of the conversation. It resolves “Alex” to the wrong person because there are two engineers with that name. These aren’t edge cases. They’re Tuesday.So you build defensively not just validation on the way out, but constraint checks before the user ever sees a confirmation:pre_checks = [ { "name": "date_not_past", "checker": "_precheck_date_not_past", "severity": "block", # Hard stop — don't even show the preview }, { "name": "schedule_conflict", "checker": "_precheck_schedule_conflicts", "severity": "warn", # Show warning but let user proceed "fallback": "_suggest_available_windows", },]The severity distinction mattered more than I expected. Some failures should stop the action entirely you cannot schedule something in the past. Others are warnings the user should see, but shouldn't be blocked by. Conflating them means either blocking things that should proceed or silently allowing things that shouldn't.Ironically, the more capable the model, the more guardrails you end up adding. Capability without constraint is just a more convincing way to fail.Latency and cost will humble youIn a demo, a four-second response feels like magic. In a system where that response triggers two tool calls and a summary generation step, you’ve just added ten seconds to something that needs to feel instant.Cost compounds the same way. A multi-step reasoning chain that hits the model three times per request looks fine in a notebook and alarming in a spreadsheet after a week of real usage.The optimizations that actually moved the needle weren’t clever they were structural. Cache the decisions that don’t change:# Table identification cache — avoid re-asking the model # which database tables to query for structurally similar requestsdef _get_cached_tables(self, query: str) -> list[str] | None: key = self._normalize_query_for_cache(query) # strips UUIDs, names, numbers entry = self._cache.get(key) if entry and (time.time() - entry["timestamp"]) return entry["tables"] return NoneAnd push deterministic computation out of the model entirely. Any query involving totals, counts, or aggregates doesn’t need a language model it needs Sum(). The model is for language. The database is for math.The hardest part is the one you can’t automateHere’s what I didn’t expect: the bottleneck was never the model. It was clarity.Vague task definition produces vague agent behavior, and no amount of prompt engineering fixes an underspecified problem. The agent reflects whatever thinking you brought to it. Sharp inputs, sharp outputs. Fuzzy inputs, confidently wrong outputs.This is what connects back to everything I wrote about whiteboarding before touching a keyboard. The same instinct that made us erase the diagram and start over, surfacing assumptions, defining failure cases, and agreeing on what “done” looks like before writing a line, that instinct doesn’t become less important when you introduce a model. It becomes more important because the model will proceed confidently through your ambiguity, and you won’t know it went wrong until something downstream breaks.AI amplifies whatever clarity you bring to it. It doesn’t supply its own.The shift that actually mattersThe most useful reframe was this: stop asking “how do I get the model to answer correctly” and start asking “how do I design a system where the model can’t easily fail.”That means smaller, more specific tasks. Explicit interfaces between steps. Reduced ambiguity at every input boundary. Visibility into what the model decided and why. It means treating the model like a powerful but literal collaborator, one that will do exactly what you describe, which means your description needs to be exact.It’s the same lesson, again, from a different angle. Think before you build. Whether your pair is a person or a model, that part doesn’t change.Building AI agents is genuinely interesting work, not because it’s easy, but because it forces precision about things software usually lets you leave vague. The prompt is the smallest part of the job. The architecture around it is where the craft lives.If you’re moving from experimenting with models to shipping real systems, expect things to break in ways that don’t produce error messages. Learn to read silent failures. That’s not a flaw in the process. That’s what the process actually is.From Prompt to Production: What Nobody Tells You About Building Real AI Agents was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.