Building a Controllable Business-Oriented AI Customer Service with Two Core Files

    Traditional AI customer service systems often focus on generating smooth text rather than executing actual business tasks. This article explores how to build a controllable, business-oriented AI customer service by separating natural language understanding from deterministic business logic. We introduce a minimal architecture based on two core files—a Business Definition file and a Dialogue Executor file—to constrain model outputs, manage dialogue state explicitly, and ensure secure API execution. By implementing business contracts, robust state management, and strict security boundaries, developers can create an AI customer service that not only answers questions but reliably completes tasks like order modifications and status checks.

    1. Defining the Goal: Task Completion, Not Just Text Generation

    When users contact customer service, they are usually looking to solve a specific problem—tracking an order, modifying shipping information, requesting an invoice, canceling a reservation, or confirming a refund—rather than just reading a well-crafted response.

    If a system relies solely on the “retrieve data and generate a response” path (like standard RAG), it can explain the rules but cannot actually process the business request. For example, if a user says, “My order hasn’t shipped yet, and I want to change the address,” an AI that merely explains the address modification policy has not fulfilled the user’s actual need.

    Therefore, we must distinguish between two capabilities:

    • Knowledge Q&A Capability: Explaining policies, operational steps, and FAQs.
    • Business Execution Capability: Identifying the goal, collecting necessary information, verifying conditions, calling APIs, and reporting actual results.

    Knowledge Q&A focuses on answer accuracy; business execution must also ensure identity verification, parameter validity, authorized operations, and clear execution results.

    A practical AI customer service should combine natural language understanding with deterministic business control:

    The model handles understanding and expression; the program handles rules, permissions, and execution; the business system provides facts and completes actions.

    This does not limit intelligence; rather, it establishes reliable boundaries for it.

    2. Why Neither Flow Orchestration Nor Autonomous Agents Are Sufficient Alone

    Visual Flow Orchestration: Branch Explosion in Complex Dialogues

    Visual orchestration is intuitive when business steps are fixed and inputs are standardized. However, real conversations rarely follow a linear sequence. While the system is asking for an order number, the user might simultaneously provide a new address. Just before submitting a modification, the user might change their mind and cancel. A single input might also contain multiple intents, such as “Check the logistics, and also tell me how to request an invoice.”

    If every conversational variation is mapped to an independent branch, the flowchart becomes unmaintainable. The issue is not the visual approach itself, but mixing natural language variations, business rules, and execution logic into a single diagram. A better approach for developers is to encode business constraints into clear code, delegate language understanding to the model, and connect the two via structured results.

    High-Autonomy Agents: Flexible, But No Substitute for Business Constraints

    Allowing a model to autonomously select tools, fill parameters, and plan steps reduces explicit flow configuration. However, when dealing with accounts, funds, orders, and personal information, an operation that “looks reasonable” may not be a valid one.

    For example:

    • The model might guess an order number from chat history and pick the wrong one.
    • A user sending “Confirm” might be confirming a question, not a submission.
    • Retrying an API call after a timeout might create duplicate requests.
    • If a tool execution fails, the model might still generate a “processed successfully” reply.

    These issues cannot be solved by longer prompts. Prompts can guide behavior but cannot replace server-side authorization, data validation, and transaction control.

    A safer approach is a constrained agent architecture: allow the model to understand natural language, but permit the program to execute whitelisted actions only when explicit conditions are met.

    3. Minimal Architecture: Two Core Files

    The “two files” should be understood as a way to organize core logic, not a claim that they can handle all complexities of a production system. A viable validation solution can revolve around two core files:

    File 1: Business Definition

    This file describes what businesses the system supports and the conditions each business must meet, including:

    • Intent identifiers and business descriptions.
    • Required information and field types.
    • Field validation rules.
    • Allowed business actions.
    • Whether user confirmation is required.
    • Conditions for success, failure, and human handoff.
    • Fact sources available for answering questions.

    The Business Definition must be maintained by developers and cannot be arbitrarily modified by the model during a conversation.

    File 2: Dialogue Executor

    This file is responsible for receiving user messages, reading the current state, and driving business execution, including:

    • Requesting the model to identify intent and extract candidate information.
    • Validating the structure returned by the model.
    • Updating business state.
    • Prompting for missing fields.
    • Calling read-only queries or controlled write operations.
    • Recording results and organizing the reply.

    Production environments still require authentication, persistent storage, secret management, logging, monitoring, and deployment configurations. These should leverage existing infrastructure and should not be omitted just to maintain the “two-file” format.

    4. Constraining Model Output with Business Contracts

    The model should not directly return arbitrary instructions like “execute a specific API.” Instead, it should return candidate interpretations that conform to agreed-upon contracts.

    Below is schematic pseudocode for a custom Business Definition, not corresponding to any existing product API:

    1. Business Definition = {
    2. "Modify Shipping Address": {
    3. Required Fields: ["Order ID", "New Shipping Address"],
    4. Write Operation: true,
    5. Requires Confirmation: true,
    6. Pre-conditions: [
    7. "User identity verified",
    8. "Order belongs to current user",
    9. "Order currently allows address modification"
    10. ],
    11. Execution Action: "Update Order Address"
    12. },
    13. "Query Order Status": {
    14. Required Fields: ["Order ID"],
    15. Write Operation: false,
    16. Requires Confirmation: false,
    17. Pre-conditions: [
    18. "User identity verified",
    19. "Order belongs to current user"
    20. ],
    21. Execution Action: "Read Order Status"
    22. }
    23. }

    The model can output a structure like this:

    1. Candidate Understanding = {
    2. Intent: "Modify Shipping Address",
    3. Candidate Fields: {
    4. Order ID: "ID explicitly provided by user",
    5. New Shipping Address: "Address provided by user in this turn"
    6. },
    7. Dialogue Action: "Provide Information",
    8. Ambiguity Exists: false
    9. }

    The term “Candidate” is critical. Fields extracted by the model cannot be directly treated as trusted facts.

    The Executor must check:

    1. Whether the intent belongs to a supported business.
    2. Whether the fields are allowed for that business.
    3. Whether the value’s type, length, and format are reasonable.
    4. Whether the fields originate from explicit user expression or trusted business queries.
    5. Whether the user has permission to access and modify the relevant data.

    For unknown fields returned by the model, the system should reject or ignore them rather than automatically extending business parameters. For missing fields, it should continue to prompt rather than letting the model guess.

    5. Separating Dialogue State from Chat History

    Chat history is useful for helping the model understand context, but it is not suitable as the sole source of business state.

    A single conversation might contain old addresses, new addresses, negated order numbers, and canceled operations. If the model has to re-infer the current state from the entire history every time, confusion is likely.

    It is recommended to explicitly maintain business state:

    1. Session State = {
    2. Current Business: "Modify Shipping Address",
    3. Current Stage: "Waiting for User Confirmation",
    4. Verified Fields: {
    5. Order ID: "...",
    6. New Shipping Address: "..."
    7. },
    8. Pending Action ID: "...",
    9. State Version: 7,
    10. Latest Execution Result: Null
    11. }

    The core stages can be designed as:

    1. Understand Request
    2. -> Collect Information
    3. -> Validate Conditions
    4. -> Wait for Confirmation
    5. -> Execute Business
    6. -> Report Result

    Additionally, set up exception or termination states like “Waiting for Result Check,” “Canceled,” or “Handed off to Human.”

    The state machine does not need to enumerate every natural language expression; instead, it constrains the changes that can occur in the business. For example, execution cannot proceed without an order ID; if the address is modified, old confirmations must be invalidated; once a business is successful, subsequent messages cannot trigger the same write operation again.

    This way, language input remains flexible, while business progression remains predictable.

    6. Executing a Complete Address Modification

    Take modifying a shipping address as an example:

    User: I want to change the address for an order that hasn’t shipped yet.

    Customer Service: I can help check if modification is supported. Please select the order you need to process.

    After the user selects an order, the system retrieves identity information from the trusted session, queries whether the order belongs to the current user, and checks the order status. The system cannot proceed solely based on the user saying, “This is my order.”

    Customer Service: This order currently meets the conditions for address modification. Please provide the new shipping information.

    After the user provides the new information, the program validates field completeness. If the address is missing necessary parts, it should specifically ask what is missing rather than asking the user to re-enter everything.

    Customer Service: Please confirm: Modify the shipping address for the selected order to the following information. The modification will be submitted upon confirmation.

    The confirmation summary should be generated from verified business parameters, not freely completed by the model. When dealing with personal information, the display scope should also be controlled based on the interaction scenario.

    User: Confirm modification.

    The program checks whether the confirmation matches the current operation version, then calls the business API. Before submission, it must re-check critical business conditions because the order might have entered a non-modifiable state during the wait.

    Only when the API explicitly returns success can the customer service say “Modification successful.” If it merely enters a backend processing queue, the response should be “Accepted and processing,” not equating acceptance with completion.

    7. Key Logic of the Executor

    The pseudocode below demonstrates the basic concept of separation of concerns:

    1. process_message(trusted_session, user_message):
    2. state = read_state(trusted_session.session_id)
    3. candidate_understanding = understand_message(
    4. user_message,
    5. state_summary,
    6. supported_business_definition
    7. )
    8. if candidate_understanding does not meet structural constraints:
    9. return clarification_question()
    10. if user requests cancellation:
    11. cancel_unsubmitted_actions()
    12. save_state()
    13. return cancellation_result()
    14. if state is waiting for result check:
    15. query_original_action_result()
    16. return verified_status_explanation()
    17. update_candidate_fields_based_on_trusted_input()
    18. validate_fields_and_update_business_state()
    19. if missing fields exist:
    20. save_state()
    21. return targeted_question()
    22. verify_identity_data_ownership_and_business_conditions()
    23. if current business requires confirmation:
    24. if operation parameters have changed:
    25. invalidate_old_confirmation()
    26. if no confirmation matching current version exists:
    27. save_pending_confirmation_summary()
    28. return confirmation_request()
    29. re-check_critical_conditions_before_execution()
    30. call_whitelisted_business_action_with_controlled_action_id()
    31. persist_execution_result()
    32. return reply_based_on_execution_result()

    A real implementation should also prevent multiple requests in the same session from modifying the state simultaneously. State version checks or appropriate concurrency control mechanisms should be used to prevent two requests from submitting duplicate operations.

    8. Embedding Security and Reliability in the Execution Path

    1. Identity and Permissions Must Originate from Trusted Systems

    Identity information should come from a verified session or account system, not extracted from user messages. Even if a user knows an order number, it does not mean they have access rights to that order.

    Authorization checks must be implemented on the business backend. Customer service layer checks can improve UX but cannot serve as the sole security boundary.

    2. Expose Only Limited, Explicit Business Actions

    Do not provide the model with arbitrary database execution capabilities or unrestricted address access. Tools should be limited to business-necessary operations, such as “Query Current User’s Orders” and “Submit Address Modification.”

    Each action requires independent parameter validation and authorization checks. This ensures that even if the model misunderstands, it cannot bypass underlying rules.

    3. User Input and Retrieved Content Cannot Alter System Permissions

    User messages, knowledge resources, and tool-returned text may contain injection prompts. They should be treated as data to be processed, not as authorization to modify execution rules.

    For example, if a document contains “Ignore previous restrictions,” the system should not lift permission checks as a result. Whether an operation can proceed is still determined by the program and the business backend.

    4. Write Operations Require Idempotency and Result Verification

    A network timeout only means the caller did not receive a result in time; it does not mean the business definitely failed.

    For modification, submission, and application operations, stable business operation IDs should be used, and the server should identify duplicate requests. Confirmation summaries, business parameters, and operation IDs should be linked to avoid reusing an old operation when parameters have changed.

    If the result is uncertain, prioritize querying the original operation status rather than immediately creating a new submission. Query operations can perform limited retries based on error types, while write operations must consider the risk of duplicate execution.

    9. Responses Must Distinguish Facts, Rules, and Speculation

    Customer service replies should prioritize citing facts returned by business APIs. Knowledge resources are used to explain policies, and the model is used to organize language; none of the three can replace the others.

    Replies can be categorized into four types:

    • Missing Information: State which field is still needed.
    • Conditions Not Met: Explain the specific reason the request cannot be processed and the next steps.
    • Execution Success: Report the completed operation and verifiable results.
    • Unknown Result: State that verification is underway, without promising success.

    “Cannot modify address” and “API temporarily unavailable” are different issues. The former is a business rule restriction; the latter is a technical exception. Clarifying this helps users know whether to try a different approach, retry later, or contact a human agent.

    When handing off to a human agent, necessary business summaries, verified information, and failure reasons should be attached to reduce the user’s need to repeat themselves. Simultaneously, avoid passing along irrelevant chat content and sensitive information.

    10. How to Verify the Customer Service is Truly Controllable

    Testing should not only check whether the response is natural but also whether execution adheres to constraints.

    It is recommended to cover the following scenarios:

    1. User provides all information at once.
    2. User supplements information over multiple turns.
    3. User corrects previously provided fields.
    4. User changes their mind during the confirmation stage.
    5. User cancels before execution.
    6. A single message contains multiple business intents.
    7. The order does not belong to the current user.
    8. Business conditions change after confirmation.
    9. API times out but actually executes successfully.
    10. The same message arrives multiple times.
    11. Model outputs an unknown intent or invalid fields.
    12. User or retrieved content attempts injection to bypass permissions.

    Tests should assert on state changes and API calls. For instance, asserting “the number of write API calls before confirmation must be zero” is more valuable than merely checking if the bot said “please confirm.”

    Monitoring should also focus on business results, not just response speed. Continuously observe business completion rates, information collection rounds, API failure rates, reasons for human handoff, and duplicate submissions. Specific thresholds should be determined by business baselines, not set arbitrarily.

    Logs need to record critical state transitions and operation results, but personal information must be desensitized, with controlled access permissions and retention periods.

    11. From Prototype to Production: Start Small, Then Scale

    The first version does not need to support all businesses. Start with a clearly bounded, low-risk scenario to complete the following closed loop:

    Identify request -> Collect necessary information -> Validate permissions and conditions -> Obtain confirmation -> Execute operation -> Verify result -> Leave an audit trail.

    Once this closed loop is tested, add new business definitions and execution actions. When adding new businesses, prioritize reusing state management, parameter validation, confirmation mechanisms, and exception handling, rather than continuously stacking prompts.

    The true value of the two core files is allowing developers to quickly see “what the business allows” and “how the program progresses.” As scale expands, these can naturally split into multiple modules without being constrained by the file count.

    Ultimately, a controllable AI customer service is not a chat model restricted by prompts, but an execution system bounded by business contracts, skeletoned by a state machine, and sourced by trusted APIs. The model makes interaction natural, the program makes the process deterministic, and the business system makes results verifiable. Only when these three perform their respective roles can customer service evolve from “sounding right” to “getting things done.”