Home Projects Portfolio Dashboard Export PDF Log in

Mastering Conversational Flows: Precision in NLU and Deterministic State for WhatsApp Bots

Building robust conversational AI often presents a delicate balance: leveraging the flexibility of Large Language Models (LLMs) while maintaining deterministic control over critical user flows. In the cronix project, focused on automating interactions via a WhatsApp bot, we recently tackled several challenging issues that underscore this balance, particularly concerning Natural Language Understanding (NLU) and state management in complex operations like rescheduling.

The Challenge of Ambiguity in Conversational AI

Conversational AI systems constantly grapple with the inherent ambiguity of human language. Users might use varied phrasing, omit crucial details, or introduce typos. For a bot, interpreting intent and maintaining context across multiple turns can be a significant hurdle. This was particularly evident in our bot's rescheduling feature, which initially relied heavily on LLM interpretation, leading to unpredictable outcomes.

From Ambiguity to Precision: Key Improvements

Our recent work focused on several key areas to enhance the bot's reliability and user experience:

Re-engineering Deterministic Rescheduling (The Critical Fix)

Previously, our rescheduling flow suffered from several issues. Phrases like "reagendarla" (reschedule it) often broke rigid regex patterns due to enclitics, causing the bot to misinterpret the intent. Furthermore, the sub-dialogue wasn't sticky, meaning the bot frequently lost context, and the LLM's suggested rescheduling often didn't align with our deterministic recovery paths.

To resolve this, we shifted control away from a purely LLM-driven approach for critical actions. We implemented a multi-turn, state machine-based resolveRescheduleTurn function. This function now explicitly manages the sub-dialogue, progressively collecting date and time information. Regex patterns were made more resilient (\w*) to handle linguistic variations. The LLM's role evolved to guide the conversation and validate input, allowing a simple "yes" from the user to trigger a highly predictable and deterministic rescheduling action. This ensures that context is maintained throughout the conversation and actions are reliably executed.

Refining Time Perception for Clarity

Ambiguous time inputs, such as a user simply stating "at 5," were often interpreted as 5 PM (17:00). While sometimes correct, this default could be misleading for business hours. We improved the parsing logic to better handle these cases, allowing explicit meridians (e.g., "5 am") to take clear precedence, reducing misinterpretations.

Accent-Insensitive Service Recognition

Our bot struggled to recognize service names if users omitted accents (e.g., typing "electronica" instead of "Electrónica"). The serviceNamedIn function was updated to be accent-insensitive, significantly improving the bot's ability to match services accurately and enhancing overall NLU robustness.

Enhancing Typo Tolerance for Dates

Minor grammatical typos, like "para e 23" instead of "para el 23" (for the 23rd), previously caused date parsing failures. The bareDay parsing logic was refined to tolerate such common article-related typos, making date extraction more forgiving and user-friendly.

Implementing Deterministic Flows with State Machines

The most significant change involved adopting a state machine pattern for critical multi-turn dialogues like rescheduling. This pattern provides a clear, predictable flow, ensuring that necessary information is collected systematically.

Here’s a conceptual TypeScript example demonstrating a simplified state machine for a multi-turn rescheduling process:

enum RescheduleState {
  Idle,
  WaitingForDate,
  WaitingForTime,
  Confirmation
}

interface RescheduleContext {
  state: RescheduleState;
  proposedDate?: string;
  proposedTime?: string;
}

function handleRescheduleInput(input: string, context: RescheduleContext): [string, RescheduleContext] {
  switch (context.state) {
    case RescheduleState.Idle:
      if (input.includes("reschedule")) {
        return ["What date?", { ...context, state: RescheduleState.WaitingForDate }];
      }
      break;
    case RescheduleState.WaitingForDate:
      const dateMatch = input.match(/on (\w+ \d+)/i);
      if (dateMatch) {
        return ["What time?", { ...context, state: RescheduleState.WaitingForTime, proposedDate: dateMatch[1] }];
      }
      return ["Please provide a valid date.", context];
    case RescheduleState.WaitingForTime:
      const timeMatch = input.match(/at (\d+(am|pm)?)/i);
      if (timeMatch) {
        const newContext = { ...context, state: RescheduleState.Confirmation, proposedTime: timeMatch[1] };
        return [`Confirm reschedule on ${newContext.proposedDate} at ${newContext.proposedTime}?`, newContext];
      }
      return ["Please provide a valid time.", context];
    case RescheduleState.Confirmation:
      if (input.toLowerCase() === "yes") {
        // Logic to update appointment, e.g., in a Supabase backend
        return [`Appointment updated to ${context.proposedDate} at ${context.proposedTime}.`, { ...context, state: RescheduleState.Idle }];
      }
      return ["Reschedule cancelled.", { ...context, state: RescheduleState.Idle }];
  }
  return ["I'm sorry, I don't understand.", context];
}

This handleRescheduleInput function, working with RescheduleState and RescheduleContext, demonstrates how a state machine guides the user through each step. It ensures that the bot collects and validates necessary information sequentially, providing a robust and predictable experience, which is crucial for actions that involve external data modifications, such as updating an appointment in a backend database like Supabase.

Conclusion

Our journey with the cronix WhatsApp bot reinforced that while LLMs offer incredible flexibility, critical conversational flows demand deterministic state management and highly refined NLU. By strategically combining LLM capabilities with structured state machines and detailed NLU improvements, we've significantly enhanced the bot's reliability, accuracy, and overall user experience. This approach ensures that even complex multi-turn interactions are handled with precision and predictability.


Generated with Gitvlg.com

Mastering Conversational Flows: Precision in NLU and Deterministic State for WhatsApp Bots
Luis Romero

Luis Romero

Author

Share: