Build a Controllable AI Customer Service System in Code, Without Low-Code Platforms
Low-code LLM orchestration tools are fast for prototypes, but production customer service often needs stronger flow control, testing, and customization. This article explains a code-first architecture: layered intent recognition, a finite-state machine for multi-branch workflows, constrained prompting, and engineering practices for observability, evaluation, RAG, human handoff, and safety.
1. Why write code instead of using a low-code platform
Low-code orchestration platforms for LLM-based customer service have become popular. Visual workflow editors, drag-and-drop nodes, and variable passing can produce a prototype quickly. After real production launch, many teams hit the same issues:
- Weak process control. Visual orchestration fits simple linear flows. Once business branches exceed a dozen, the canvas becomes hard to maintain, and versioning often depends only on the platform’s snapshot mechanism.
- Hard debugging and testing. Root-causing intent errors, rolling back multi-turn dialogue state, and running batch regression tests are awkward in a graphical UI.
- Limited deep customization. Node types are a closed set. Custom retrieval, canary release, or A/B testing often hits the platform’s capability limits.
Building in code puts intent recognition, orchestration, and state management in your own repository, with unit tests, code review, and CI. This article targets a customer-service bot that can actually complete work, and breaks down the core technical approach.
2. Overall architecture
A controllable intelligent customer-service system has four layers:
User input│▼┌─────────────┐│ Ingress │ Web / API / messaging channel adapters├─────────────┤│ Intent │ Classification + entity extraction + confidence├─────────────┤│ Orchestration │ State machine / multi-branch flow engine├─────────────┤│ Execution │ Knowledge retrieval, business APIs, reply generation└─────────────┘│▼Session state store (session ID, current node, slot variables, history summary)
The design principle: the LLM handles understanding and expression; code handles control and execution. Use the model for what it is good at, and keep process determinism in a state machine.
3. Intent recognition: layered, not one-shot
Low-code platforms often configure a single “intent node” and dump every intent into one prompt. Accuracy drops once intents exceed twenty or thirty. A better approach is hierarchical intent recognition.
3.1 Two-level structure
Layer one is domain classification: pre-sales, after-sales tickets, account issues, or chitchat. Layer two is fine-grained intent within the domain. Each layer faces few candidates, so accuracy improves.
Illustrative code:
INTENT_TREE = {"pre_sales": ["product_price", "feature_comparison", "trial_request"],"after_sales": ["refund_request", "status_inquiry", "escalation"],"account": ["password_recovery", "change_binding", "close_account"],}def detect_intent(user_input: str, context: dict) -> str:domain = llm_classify(user_input, list(INTENT_TREE.keys()), context)if domain == "chitchat":return "chitchat"intent = llm_classify(user_input, INTENT_TREE[domain], context)return intent
3.2 Small model for first-pass, LLM as fallback
For frequent, simple intents (for example, “refund”), a lightweight classifier or rules can hit first and return immediately; uncertain samples go to the LLM. That cuts cost and latency.
3.3 Confidence and fallback
Every intent prediction should include a confidence score. Below threshold, do not guess—clarify: “Are you asking about order status, or requesting a refund?” That is central to controllability: one extra question is better than taking the wrong branch and forcing the user to restate the problem.
4. Multi-branch flow engine: the state machine is the foundation
Intent answers “what the user wants.” The flow engine answers “in what steps.” Model business processes as a finite-state machine (FSM).
4.1 Declarative flow config
FLOW = {"refund_request": {"start": "verify_order","nodes": {"verify_order": {"slots": ["order_id"],"ask": "Please provide your order number.","next": {"check_ok": "confirm_reason", "check_fail": "handoff"},},"confirm_reason": {"slots": ["reason"],"ask": "What is the reason for the refund?","next": {"confirm_submit": "execute_refund", "cancel": "end"},},"execute_refund": {"action": "call_refund_api","next": {"success": "notify_result", "fail": "handoff"},},},}}
Benefits:
- The flow is documentation; product can review it directly.
- Each node declares required slots, so key fields are not missed.
- Branch jumps are explicit, so the model cannot freely derail the process.
4.2 Slot filling and interruptions
Real users do not follow the script. While asked for an order ID they may say, “I don’t remember it, but I bought it yesterday afternoon.” Each node should support:
- Slot inheritance: fill known slots from history or account data.
- Interrupt and resume: save flow state if the user changes topic; after the new issue, ask whether to continue.
- Escape hatch: if a node fails to fill slots for two consecutive turns, escalate to a human.
4.3 Session state
Persist session state in a database or cache: session ID, current flow name, current node, filled slots, and a summary of the last N turns. Restarts or a user returning the next day can then resume cleanly.
5. Prompt engineering: constrain model behavior
In a self-built system, the LLM is narrowed to three jobs, each with a dedicated prompt:
- Intent prompt: candidate list, decision rules, few-shot examples; require structured JSON; forbid labels outside the list.
- Slot extraction prompt: fields to extract, format rules (for example, order ID must be digits only); return null if missing.
- Reply prompt: current node context, knowledge snippets, tone guidelines; keep replies short and do not promise anything outside the flow.
An important technique is putting flow constraints in the system prompt: “Answer only within the current step. If the user asks something outside the flow, respond politely and guide them back.” Combined with FSM node transitions, that is dual insurance.
6. Engineering practices for production
- Observability. Log intent, confidence, state-machine transitions, and the final action for every request so bad cases can be analyzed.
- Canary and evaluation. Keep a labeled dialogue set as a regression suite. After prompt or flow changes, score automatically so a local fix does not break three other paths.
- Knowledge retrieval. For general Q&A, use retrieval-augmented generation: chunk enterprise docs, embed them, store in a vector database or hosted retrieval service, and cite sources in replies for human review.
- Human handoff loop. Every automated path should have a handoff exit. Pass a full context summary to the agent so the user does not repeat themselves.
- Safety boundary. Sensitive actions such as refunds or changing a bound phone number must be re-checked in code, not executed from model output alone.
7. Conclusion
Building intelligent customer service without a low-code platform means taking orchestration back into engineering: layered intent for accuracy, an FSM for deterministic flows, prompts that bound expression, plus logging, evaluation, and human fallback. Upfront cost is higher than dragging nodes on a canvas, but you get testable, rollback-friendly, extensible engineering assets—the right path for production.
