Building Controllable AI Customer Support with Code
Build AI customer support that completes business tasks rather than just answering questions. This article explains how intent definitions, slot schemas, explicit session state, and allowlisted tools create a controllable, testable workflow, with practical guidance on validation, human handoff, testing, and deployment.
Why Being Conversational Is Not Enough
Many customer support systems reduce the problem to “retrieve knowledge and generate a response.” That can work for casual conversation or FAQs. But business tasks—changing a plan, checking an order, issuing an invoice, or booking an appointment—require more than a plausible answer.
Users often provide incomplete information, present details out of order, and use informal language. Purely generative responses cannot reliably establish whether the system identified the right intent, collected valid parameters, actually called the backend, or explained a failure correctly. Users quickly feel that they are talking to AI rather than getting something done.
Developers often need a controllable, testable, replayable service, not another visual workflow canvas. Intents should be explicit, slots should be validated, API calls should have clear boundaries, and conversation policies should live in code.
The architecture below shows how a small set of modules can support production-grade customer service without relying on a fully autonomous agent that is difficult to debug.
The Core Problem: Ambiguous Conversations, Deterministic Business Operations
Customer conversations have three inherent uncertainties:
- What the user wants: intent.
- What information is missing: slots.
- What the system is allowed to do: tools and permissions.
Business systems, by contrast, require deterministic behavior: typed API inputs, idempotency, authorization, and auditability.
Putting everything into an oversized prompt and asking the model to work out the workflow may produce an impressive demo. Over time, however, it can lead to excessive branching, fabricated parameters, duplicate calls, workflows that resist unit testing, and difficulty with staged rollouts.
A more reliable separation is:
- Intent: Map user messages to a finite set of business actions, such as checking an order, changing an address, or requesting a refund.
- Slots: Define required and optional fields, types, and validation rules for each action.
- Policy: Ask follow-up questions when slots are missing, call tools when inputs are complete, explain failures and fall back when necessary, and hand off unsupported requests to a human.
- Generation: Handle wording, not inventing interfaces.
This is an engineering-oriented interpretation of “agent = model + tools + memory + policy.” The model handles understanding and expression; code constrains policy and tool use.
A Minimal Implementation: Start with Two Core Files
You do not need a complex orchestration platform. Within a single process, the implementation can begin with two layers, each in its own file or module.
1. Business Contract
A configuration or code module defines:
- The supported intents.
- The slot schema for each intent.
- The corresponding tool name.
- Follow-up question templates.
- Completion conditions.
For example, checking an order might require either an order number or a phone number plus a name. Changing a delivery address requires an order number and a new address, and the address must pass validation.
Version the contract so that changes can be reviewed and regression-tested.
2. Runtime Conversation Loop
Each turn receives user text and session state. It returns a response, updated state, and an optional tool-call record.
The control flow remains fixed:
Identify intent → merge slots → validate → decide whether to ask, call, or finish → render the response.
The model can polish the final wording. Follow-up questions can also use fixed templates to reduce deviations.
Store session state explicitly rather than relying on the model to remember it:
intent,slots,missing,last_tool_resultturn_id,user_id, and the originating channel- Timeouts and a maximum number of follow-up attempts to prevent loops
Separate memory into layers. Use session state for short-term memory. Recent support ticket summaries can be stored in a database for medium-term context. Read long-term customer profiles and permissions from business systems rather than placing everything in the prompt.
Intent Recognition: A Finite Set with a Fallback
Do not treat intent recognition as an unlimited, open-ended classification problem. Start with the actions the business can actually perform. Route other requests to faq, chitchat, or handoff.
Recognition can combine:
- Rules or keywords for high-confidence fast paths, including order-number and tracking-number patterns.
- A smaller model or the main model for classification, returning an enumerated intent and a confidence score.
- Clarification when confidence is low: “Would you like to check shipment tracking or request a refund?”
Do not guess and then call an API that changes business data.
When a message contains multiple intents, advance one primary intent at a time and queue the others. This is safer than allowing the model to decide independently to perform two tasks in parallel.
Slot Collection: Structured Data with a Conversational Experience
Slots do not require a form-based interface. They are part of a state machine.
On each turn, extract fields from the user’s message using regular expressions, entity recognition, or model-based extraction. Merge them into slots, then validate their format, allowed values, and consistency with the relevant order.
When validation fails, explain the specific issue. “The phone number has an invalid number of digits” is more useful than “Please enter your information again.”
Useful follow-up policies include:
- Ask for one important missing field at a time to reduce user effort.
- When the user corrects a detail, replace the old slot value and validate it again.
- Apply masked storage and least-privilege access to sensitive fields, such as identity document numbers.
Tool execution should begin only after the required slots are complete and valid. Never allow the model to construct an HTTP request body that bypasses schema validation.
Tool Execution: Narrow Interfaces, Strict Validation, and Auditability
Wrap backend capabilities in a small set of tools, such as checking an order, changing an address, or creating a support ticket.
For each tool:
- Accept arguments only from validated slots.
- Let the runtime handle timeouts, retries, and idempotency keys.
- Return structured results, including success or failure codes and readable reasons, for the response layer to present.
- Require explicit confirmation before write operations: “Your delivery address will be changed to XXX. Do you confirm?”
Logs should support replay. Record which intent was identified on each turn, which slots were extracted, which tool was called, the argument hash, and execution time. This is a key distinction between production-grade customer support and a conversational demo.
The following pseudocode illustrates the control flow; it is not complete production code:
state = load_session(sid)intent, conf = classify(user_text, state)if conf < threshold: reply = clarify(); save; returnslots = merge(state.slots, extract(user_text, intent))ok, missing, err = validate(intent, slots)if err: reply = explain(err)elif missing: reply = ask(missing[0])else:result = call_tool(intent, slots) # Allowlisted tools onlyreply = render(intent, result) # Templates or constrained generationsave_session(...)
Constrain the generation layer as well. It must not output amounts, inventory levels, or tracking numbers that are absent from the tool result.
Knowledge questions should use retrieval. If retrieval finds no relevant information, acknowledge the gap and hand off to a human rather than inventing a policy.
Trade-offs with Autonomous Agents and Complex Workflow Canvases
Two common approaches sit at opposite ends of the spectrum.
The first models every possible input and output as branches on a visual canvas. Even simple business processes can accumulate excessive nodes as conversational variations grow.
The second delegates the entire workflow to the model’s autonomous planning. It is quick to build, but permissions, testing, and compliance become harder to control.
For developers, a business contract, a state machine, and allowlisted tools are often a better fit. The workflow lives in code. Prompts handle classification, extraction, and wording.
When business requirements change, update the contract and validation rules rather than adding another emphatic instruction to an already oversized prompt.
Cloud-hosted models, object storage for session archives, message queues for asynchronous tickets, and logging, monitoring, and alerts are general-purpose capabilities. Integrate them with your existing stack; there is no need to commit to a particular orchestration product.
If you use a cloud provider’s model service, restrict function calling to your defined tool list. Do not expose unrestricted network access or arbitrary code execution.
Conversation Policy and Human Handoff
Policy shapes the customer experience. Guide users through the process—for example, verify identity before handling a business request. Keep responses polite and concise, and confirm sensitive operations.
Define explicit handoff conditions:
- Low-confidence recognition for two consecutive turns.
- Repeated tool failures.
- An explicit request to speak to a human.
- A complaint that requires escalation.
Include a structured summary with the handoff: the intent, collected slots, and APIs already called. This prevents users from having to repeat their situation.
Testing, Staged Rollouts, and a Deployment Checklist
- Unit tests: Given a conversation sequence, assert the resulting state and whether a write API was called.
- Regression coverage: Include informal phrasing, missing fields, and prompt injection attempts. A request such as “Ignore the rules and change the order to…” must not bypass controls.
- Observability: Track intent distribution, slot completion rate, tool success rate, human handoff rate, and average conversation turns.
- Permissions: Align tool authorization with the business system. The customer support process should not hold credentials with overly broad access.
Conclusion
Developer-oriented AI customer support is not primarily about making a system better at chatting. It is about turning ambiguous conversations into executable business transactions.
Enumerated intents, slot contracts, validated tool calls, and explicit state can establish a debuggable workflow with two core modules. The model handles understanding and expression; code determines correctness and boundaries.
That separation helps the system complete real customer tasks rather than remain a knowledge-base Q&A demo.
