Building a Controllable AI Customer Support System in Two Files

    Learn how to build a code-driven AI customer support system that separates language understanding from business execution. This two-file design uses declarative workflows and a lightweight engine for intent classification, slot filling, API calls, and responses, with practical guidance on validation, testing, session management, and deployment.

    1. Why Platform-Based Customer Support Can Fall Short for Developers

    Rapid advances in large language models (LLMs) have made AI customer support a common feature in business applications. A typical implementation uses a visual orchestration platform: drag-and-drop nodes define conversation flows, while prompts handle intent recognition. These tools can be accessible to non-programmers, but they introduce several challenges from an engineering perspective.

    Limited control. A visual workflow makes the process visible, but model inputs and outputs remain ambiguous. A single user message may match multiple intents, and a model may produce unexpected responses at a branching point. As the number of nodes grows, combinations of conditions can increase exponentially, making runtime behavior difficult to predict.

    Difficult debugging. Traditional software engineering relies on unit tests, logs, and breakpoint debugging. In visual platforms, logic is often distributed across prompts in separate nodes, making version control and automated testing difficult. Troubleshooting production issues may depend heavily on manually reproducing conversations.

    Complexity does not disappear. “No-code” does not necessarily mean simple. Even moderately complex workflows, such as returns or billing inquiries, require numerous branches, variables, and fallback rules. Configuration can take as much effort as writing code, without offering the same expressiveness or tooling.

    For developers, a more natural approach is to treat customer support as a regular software project. Define workflows in code, call models through an adapter, and execute business APIs explicitly. Let the model handle language understanding and generation while code retains control over deterministic business logic.

    2. Why Knowledge-Base Q&A Is Not Enough

    Before exploring the implementation, consider the limitations of the traditional knowledge-base chatbot.

    Its typical workflow is:

    User question → retrieve relevant knowledge-base content → ask the model to compose an answer → return the answer.

    This works for informational questions such as “What is your return policy?” But customer support involves more than answering questions.

    Its real value often lies in completing business tasks. Consider this exchange:

    User: I want to find out why my order from last week has not arrived.
    Assistant: Please provide your order ID.
    User: A2024001.
    Assistant: [Calls the shipping API] Your package has reached the local distribution center and is expected to arrive tomorrow. Can I help with anything else?

    The system must identify the intent, collect the order ID, call a backend API, and compose a response from the result. This requires state management, parameter validation, and interaction with external systems—structured engineering tasks that retrieval and generation alone do not naturally solve.

    This gap is a common source of frustration: an assistant repeatedly explains policies but cannot take action.

    3. Two Common Approaches

    Platforms generally address task-oriented customer support through two approaches. Understanding their trade-offs helps clarify the code-driven design.

    3.1 Workflow Orchestration

    This approach combines intent classification with explicit conversation nodes and branches.

    Its strengths are clear, auditable paths. Its weakness is that developers must account for each branch and ambiguous input. Prompts become increasingly complex, and maintenance costs rise with business complexity.

    3.2 Autonomous Agents

    The alternative delegates more of the process to an autonomous agent:

    Agent = LLM + tools + memory + conversation strategy

    • The LLM interprets requests, makes decisions, and generates responses.
    • Tools include knowledge bases, databases, and business APIs that provide structured information or execute actions.
    • Memory maintains multi-turn context and user state.
    • Conversation strategy guides the user, collects missing information, and escalates unresolved issues to a human.

    With a capable model service, this approach can identify intents, populate parameters, invoke APIs, and respond based on their results.

    The concern is opaque decision-making. Developers may struggle to exercise fine-grained control over which API the model calls, whether its parameters are correct, and why it chooses a particular path. That uncertainty can be unacceptable in compliance-sensitive domains such as finance and transaction processing.

    4. A Code-Driven Design: Control First

    The core principle is simple: code owns the workflow; the model handles understanding.

    The design needs two core files:

    1. A workflow definition file, such as flows.py or flows.json, declaring business workflows, required slots, and API mappings.
    2. An engine file, such as engine.py, loading those definitions and driving the intent classification → slot filling → API execution → response cycle.

    Here, a slot is a structured parameter the system needs to complete a task, such as an order ID or refund reason.

    4.1 Workflow Definitions

    1. FLOWS = {
    2. "logistics_query": {
    3. "description": "Check shipment status",
    4. "slots": [
    5. {"name": "order_id", "type": "string",
    6. "prompt": "Please provide your order ID"},
    7. ],
    8. "api": "query_logistics",
    9. "reply_template": "Your package status: {status}. Expected delivery: {eta}.",
    10. },
    11. "refund_apply": {
    12. "description": "Request a refund",
    13. "slots": [
    14. {"name": "order_id", "type": "string",
    15. "prompt": "Please provide your order ID"},
    16. {"name": "reason", "type": "enum",
    17. "options": ["Quality issue", "No longer wanted", "Other"]},
    18. ],
    19. "api": "apply_refund",
    20. "reply_template": "Your refund request has been submitted. Ticket ID: {ticket_id}.",
    21. },
    22. }

    Each definition specifies the intent, required information, business API, and response template. The business process stays explicit rather than being embedded in a long prompt.

    4.2 The Engine’s Core Loop

    1. class Engine:
    2. def __init__(self, flows, llm, api_client):
    3. self.flows = flows
    4. self.llm = llm
    5. self.api = api_client
    6. self.state = {"flow": None, "slots": {}}
    7. def handle(self, user_input: str) -> str:
    8. # 1. Intent classification: ask the model to select a defined workflow
    9. if self.state["flow"] is None:
    10. intent = self.llm.classify_intent(user_input, self.flows)
    11. self.state["flow"] = intent
    12. flow = self.flows[self.state["flow"]]
    13. # 2. Slot filling: extract missing parameters from the user's input
    14. self.llm.extract_slots(user_input, flow["slots"], self.state["slots"])
    15. # 3. Check for missing parameters and ask using code-defined prompts
    16. missing = [s for s in flow["slots"] if s["name"] not in self.state["slots"]]
    17. if missing:
    18. return missing[0]["prompt"]
    19. # 4. Execute the business API call; calls can be logged and replayed
    20. result = self.api.call(flow["api"], self.state["slots"])
    21. # 5. Render the response from the actual API result
    22. return flow["reply_template"].format(**result)

    This is a minimal skeleton for the control loop. The model classifies the request and extracts parameters, while code determines when to ask for more information and when to execute the API. The final response is rendered from the API result rather than generated independently.

    4.3 How the Design Improves Control

    • Intent outputs can be validated. The model selects from a finite set of workflows. Its output must match a defined intent; an out-of-range result should trigger a fallback or human handoff.
    • Parameter validation belongs in code. Ordinary validation logic checks order ID formats and allowed enum values rather than relying on the model to follow instructions.
    • API execution follows code-defined rules. Code controls the endpoint, parameters, and execution sequence. Calls can be logged and monitored.
    • Components are directly testable. Workflow definitions and engine behavior can be covered by unit tests using fixed inputs and assertions about expected outcomes.

    The skeleton above checks whether slots are present. Intent validation and checks for parameter formats and allowed values belong in the code-level validation layer.

    5. Extensions and Production Considerations

    The two-file structure provides a starting point that can be strengthened incrementally.

    1. Fallbacks and human handoff. When intent classification confidence is low or slot collection fails over multiple turns, return an appropriate response and transfer the conversation to a human support queue.

    2. Multi-turn context management. Maintain a separate state object for each session. Clear it when the session ends or times out.

    3. Model service selection. A cloud-hosted LLM service can handle intent classification and slot extraction. The source approach includes Baidu AI Cloud’s Qianfan platform as an example. Keep provider-specific integration in the llm adapter so the business logic does not need to change when the model service changes.

    4. Knowledge-base integration. Add a knowledge Q&A intent for informational requests and route it through retrieval-augmented generation (RAG). This allows knowledge retrieval and task-oriented workflows to coexist.

    5. Monitoring and staged rollout. Record each turn’s intent, slots, and API results to support offline analysis and workflow improvement. Introduce changes through a staged rollout to a proportion of traffic.

    6. Conclusion

    Effective AI customer support is not about giving a model unrestricted freedom. It is about using the model to interpret ambiguous language while keeping business execution under code-defined control.

    Compared with visual orchestration or fully autonomous agents, this two-file approach offers a compact foundation for more controllable, testable, and debuggable support workflows. It is particularly useful for development teams that want an assistant capable of completing tasks, not merely explaining policies.

    The guiding principle is: the model handles understanding; code controls decisions and execution.