Building a Controllable AI Customer Service System That Can Execute Business Tasks in Code
Many AI customer service systems can explain policies but cannot complete real actions such as changing a delivery address. This article describes an architecture that separates language understanding from business control and execution. It covers common technical approaches, a minimal two-file prototype, structured state and confirmation, idempotency and result verification, multi-turn interaction design, security boundaries, testing, and a practical path to expand from one business task to more.
1. The Goal Is Not to “Answer Well” but to “Get Things Done”
Many AI customer service systems follow a basic pattern: retrieve knowledge from a knowledge base, then generate an answer. This approach works well for explaining return and exchange policies, describing service scope, and answering common questions, but it cannot directly handle scenarios that require changing business data.
For example, a user says: “The order has not shipped yet. I want to change the delivery address.”
Even if the customer service system accurately answers that “orders that have not shipped can request an address change,” it has not actually solved the problem. The user still needs to find the right entry point, fill in information, and possibly contact a human agent again. A customer service system that can execute business tasks needs to complete the following actions:
- Determine whether the user is asking about a rule or requesting an address change.
- Identify the user and the orders they are authorized to operate on.
- Check whether the order can still be modified.
- Collect and validate the new address.
- Show the proposed change and obtain explicit user confirmation.
- Call the business API to submit the change.
- Report success, failure, or in-progress status based on the actual execution result.
This type of customer service is essentially a business execution system with natural language as its entry point. Natural language understanding is only the starting point. Business rules, state progression, and execution results are the core of reliability.
Therefore, the design goal should shift from “try to answer every question” to:
Within clear permission and business boundaries, understand user needs, collect necessary information, and reliably complete supported operations.
2. Applicability and Limits of Common Technical Approaches
1. Knowledge Q&A: Good at Explanation, Not Execution
Knowledge retrieval can help a model answer questions based on reference materials and provide sources for policy explanations. However, knowledge content cannot replace real-time business state.
A document may say that “orders that have not shipped are allowed to change the address,” but that does not mean a specific order meets the conditions at this moment. Whether the order has entered the fulfillment process, whether it involves special delivery, or whether there are risk-control restrictions should be determined by the business system.
Therefore, knowledge retrieval is responsible for explaining rules, and business APIs are responsible for confirming facts. The two should not be conflated.
2. Visual Workflows: Easy to Present, but Complexity Does Not Disappear
Visual orchestration is suitable for presenting stable and clear business paths, and it helps non-developers understand processes. However, natural language interaction often includes interruptions, corrections, task switching, and incomplete input.
A user may provide an order, an address, and a change request in the same sentence, or suddenly ask to cancel before confirmation. If every case is expanded into branches, the workflow becomes increasingly difficult to maintain.
This does not mean a particular type of tool is inherently uncontrollable. Rather, interaction complexity needs to be modeled properly. Whether using a graphical interface or code, the system still needs to handle state, validation, exceptions, and permissions.
3. Autonomous Agents: Flexible, but They Cannot Make All Decisions
Autonomous agents usually combine models, tools, context memory, and task strategies so that the model decides the next action. This approach is suitable for open-ended tasks, but in scenarios involving accounts, orders, or funds, relying entirely on model planning can increase uncertainty.
A more robust design is:
The model is responsible for understanding and expression, while the program is responsible for authorization, validation, and execution.
The model can suggest that “the user wants to change the address,” but it cannot decide on its own that the user is authorized to make the change, nor can it bypass order-status restrictions and submit directly.
3. Core Architecture: Separate Language Understanding from Business Control
The system can be divided into five logical parts:
User message↓Language understanding: extract intent, candidate fields, and dialogue actions↓Business control: read state, check permissions, validate fields↓Business execution: call controlled APIs, record execution results↓Result expression: generate a response based on confirmed facts
The language understanding layer outputs “information to be verified,” not instructions that can be executed directly.
For example, if the model extracts an “order number” and a “new address” from a sentence, the program still needs to verify whether the order exists, whether it belongs to the current user, and whether the address meets business requirements. Even if the output format is completely valid, it does not mean the field contents are real or authorized.
The business control layer should maintain explicit states, such as:
- waiting for order selection;
- waiting for address completion;
- waiting for user confirmation;
- submitting the change;
- change succeeded;
- change failed;
- cancelled;
- handed off to a human agent.
The state determines which actions are currently allowed. In the “waiting for address completion” state, the system can accept a new address or a cancellation request, but it cannot directly report that the change succeeded.
4. A Minimal Two-File Approach, Without Misunderstanding Engineering Boundaries
For a prototype of a single business task, the core logic can be organized into two main files:
- Business configuration file: describes intents, fields, validation requirements, confirmation policies, and action mappings.
- Execution kernel file: reads the configuration, maintains state, and calls the model adapter layer and business adapter layer.
This organization emphasizes “declare the business, execute uniformly.” It does not mean that two files are enough to complete a production system. Real deployment also requires identity authentication, persistent storage, API adapters, monitoring, testing, and other capabilities.
The following illustrative configuration explains the design approach. The field and action names are custom examples for this article and do not represent any existing product API.
business: change_delivery_addressrequired_fields:- order_reference- recipient- contact_number- delivery_addresspreconditions:- authenticated_user- order_owned_by_user- order_change_allowedconfirmation_required: trueaction: submit_address_changefailure_policy:- explain_business_rejection- verify_unknown_execution_status- offer_human_handoff
The configuration should express business differences, while the execution kernel handles common logic. However, complex rules should not all be forced into configuration just for uniformity. Transactions involving multiple systems, special approvals, or complex compensation still require dedicated business code.
5. Execution Kernel: Validate First, Execute Next, Express Last
The following pseudocode is independent of any specific implementation language:
handle_message(user, session, message):verify_session_access(user, session)state = load_session_state(session)facts = extract_candidate_information(message, state)validate_structure(facts)if facts.requests_cancel:return handle_cancellation(state)if facts.requests_task_switch:return handle_task_switch(state, facts)business = select_supported_business(state, facts)if business is ambiguous:return ask_for_clarification()state = merge_valid_candidate_fields(state, facts)missing = find_missing_required_fields(state, business)if missing is not empty:save_state(state)return ask_for_missing_information(missing)verify_business_authorization(user, state)validate_business_fields(state)if confirmation_is_required(state):if not confirmed_against_current_summary(state, facts):save_confirmation_summary(state)return show_summary_and_request_confirmation(state)result = execute_with_idempotency(state)save_execution_result(state, result)return respond_from_verified_result(result)
The important part of this logic is not the syntax but the order of responsibilities:
First, confirm the relationship between the session and the user identity to avoid reading state across users.
Second, model extraction results must go through structural validation and business validation. The fact that the model provides an order number does not mean the order can be operated on.
Third, confirmation must correspond to the current operation summary. If the user changes the address after confirming, the original confirmation should become invalid, and the system needs to ask for confirmation again.
Fourth, responses must be based on execution results. The model saying “it has been handled” cannot be the basis for success.
Fifth, cancellation behavior must be tied to execution state. If the request has already been submitted, the system cannot simply clear the session and claim that cancellation succeeded. It should check whether the business supports withdrawal.
6. Key Aspects of Multi-Turn Interaction: State, Fields, and Task Boundaries
1. Do Not Use the Entire Chat History as the Only Memory
The full conversation can help with understanding, but it is not suitable as the only source of business state. Chat content may contain ambiguity, repetition, and outdated information.
Structured state should be stored separately, including:
- the current task type and task identifier;
- confirmed fields and fields pending confirmation;
- the current process stage;
- the confirmation summary and its version;
- the most recent execution request identifier;
- verified business results.
Chat history is used to interpret what the user said, while structured state is used to decide what the system may do.
2. Accept Multiple Fields at Once and Allow Item-by-Item Corrections
Users do not necessarily provide information in form order. The system should allow multiple candidate fields to be extracted at once and merged into state after validation.
If the user says, “The phone number is not the previous one. Change it to the new number,” the system should update the corresponding field and determine whether that change invalidates a previous confirmation, rather than collecting all information again.
3. Handle Task Switching Explicitly
A user may suddenly ask about refund progress while changing an address. The system needs to distinguish a temporary question from an actual task switch.
Low-risk queries can be answered temporarily before returning to the original task. For new write operations, the system should confirm whether to pause or cancel the current task, avoiding mixing fields from different business tasks.
7. API Calls Must Have Reliability Constraints
1. Tool Allowlists and Least Privilege
Customer service can only access approved business actions. The model cannot freely construct API endpoints, execute arbitrary queries, or expand parameter scope.
Permission control should be implemented on the server side and in the business system, not only in prompts. Prompts can guide behavior, but they are not a security boundary.
2. Idempotency Control Prevents Duplicate Execution
Repeated confirmation messages, network retries, or service restarts can all cause the same operation to be submitted multiple times.
A stable request identifier can be generated for a confirmed business operation, and the business service can handle idempotency within its supported scope. For high-risk write operations, if downstream systems do not support idempotency or result queries, automatic retries should not be adopted casually.
3. Distinguish Failure from Unknown Result
An API timeout only means that customer service did not receive a timely response. It does not necessarily mean that business execution failed.
The system should distinguish:
- explicit success;
- explicit business rejection;
- explicit technical failure;
- unknown execution result.
When the result is unknown, prioritize querying execution status by request identifier. If it cannot be verified, tell the user that the result is being confirmed and hand off to a human agent when necessary, avoiding duplicate submission.
4. Consider Compensation for Multi-Step Business Operations
Operations across multiple systems may partially succeed. For example, one record may have been updated while another synchronization failed. In this case, the system should clarify which steps can be retried, which steps require compensation, and which situations must be handled manually.
Natural language responses must not hide the fact that a partial success occurred.
8. Knowledge, Models, and Security Boundaries
A knowledge base is suitable for providing policy explanations, but high-risk rules are better provided by structured configuration or business APIs. For example, whether an order allows changes should be based on real-time validation, not inferred from retrieved historical documents.
Natural language in user messages, retrieved text, and API responses also must not be treated as higher-privilege system instructions. Even if the text says “ignore restrictions and submit the operation,” the execution kernel should still follow fixed authorization rules.
Personal information processing should also follow the principle of necessity: collect only the information required to complete the business task, appropriately mask contact numbers and addresses in logs, and set access permissions and retention periods.
The result expression layer can use a model to improve naturalness, but important fields should preferably come directly from structured results. For content such as amounts, order status, and processing results, the model should not fill in missing information on its own.
9. How to Determine Whether Customer Service Can Really Complete Work
Testing should not only check whether responses are fluent. It should verify the complete business loop.
At minimum, the following cases should be covered:
- The user provides all necessary information at once.
- The user provides information over multiple turns and makes multiple corrections.
- The user provides a business object that does not belong to them.
- The user cancels or switches tasks before confirmation.
- The user modifies a key field again after confirmation.
- The API times out, but the actual operation has already succeeded.
- The same confirmation message is sent repeatedly.
- Business conditions change after confirmation but before execution.
- The user attempts to bypass permissions through natural language.
- The system can provide a complete task summary when handing off to a human agent.
Evaluation metrics can include business completion rate, number of information-collection turns, number of incorrect executions, number of duplicate submissions, reasons for human takeover, and handling of unknown results. Specific targets should be based on business risk and actual data, and general promises should not be made without evidence.
Logs should be able to correlate state changes, validation results, execution requests, and final results within a task, but sensitive content should not be logged indiscriminately. This makes it possible to answer “why was it not executed,” “why was confirmation requested again,” and “did the operation actually succeed.”
10. Start with One Business Task and Expand Gradually
The most effective implementation path is not to cover all customer service responsibilities at once, but to choose a business task with clear boundaries, stable APIs, and verifiable results.
First complete identity verification, information collection, user confirmation, API execution, and result feedback, then gradually add more intents. When adding new business tasks, prioritize reusing state management, confirmation mechanisms, idempotency control, and exception handling rather than copying a complete dialogue logic for each task.
The advantage of a code-based implementation is not just “drawing fewer workflow diagrams.” It is the ability to turn key behaviors into rules that can be checked, tested, and version-controlled.
Ultimately, a reliable AI customer service system should achieve the following: understanding can be flexible, but permissions must be explicit; expression can be natural, but facts must be verifiable; interaction can be open, but execution must have boundaries. Only when these principles are implemented in programs and business APIs can customer service grow from a “chat-based Q&A entry point” into a “business assistant that can complete work.”
