Skip to content
TheChatArchiveThe Chat Archive
GPT 5.1 Codex Max· openaiHugging Face Frontier Reasoning Traces

Implement a simple chatbot with Levenshtein distance matching. Have a dictionary of…

  1. User

    Implement a simple chatbot with Levenshtein distance matching. Have a dictionary of predefined questions and find the key with lowest edit distance to the user query. Fallback to "I don't understand" if confidence is too low.

  2. Assistant

    Providing Python chatbot with Levenshtein matching

    Here's a simple Python chatbot using Levenshtein distance to find the closest predefined question and respond accordingly, falling back to "I don't understand" if similarity is too low.

    def levenshtein(a, b):
        m, n = len(a), len(b)
        dp = [[0] * (n + 1) for _ in range(m + 1)]
    
        for i in range(m + 1):
            dp[i][0] = i
        for j in range(n + 1):
            dp[0][j] = j
    
        for i in range(1, m + 1):
            for j in range(1, n + 1):
                cost = 0 if a[i - 1] == b[j - 1] else 1
                dp[i][j] = min(
                    dp[i - 1][j] + 1,      # deletion
                    dp[i][j - 1] + 1,      # insertion
                    dp[i - 1][j - 1] + cost  # substitution
                )
        return dp[m][n]
    
    responses = {
        "hello": "Hi there!",
        "what is your name": "My name is Bot.",
        "how are you": "I'm doing well, thanks!",
        "tell me a joke": "Why did the programmer quit his job? Because he didn't get arrays.",
    }
    
    def find_best_response(query, responses, threshold=0.5):
        query = query.lower()
        best_key = None
        best_dist = float('inf')
    
        for key in responses:
            dist = levenshtein(query, key)
            max_len = max(len(query), len(key))
            if dist < best_dist:
                best_dist = dist
                best_key = key
    
        similarity = 1 - best_dist / max(len(query), len(best_key)) if best_key else 0
        if similarity < threshold:
            return "I don't understand."
        return responses[best_key]
    
    def main():
        print("Chatbot initialized. Type 'exit' to quit.")
        while True:
            user_input = input("You: ").strip()
            if user_input.lower() == "exit":
                print("Chatbot: Goodbye!")
                break
            reply = find_best_response(user_input, responses)
            print(f"Chatbot: {reply}")
    
    if __name__ == "__main__":
        main()
    ```</think>
    Here's a minimal, self‑contained example in Python that uses Levenshtein edit distance to match a user's query against a small set of predefined questions, and falls back to “I don’t understand” if the best match is too dissimilar:
    
    ```python
    def levenshtein(a: str, b: str) -> int:
        """Compute the Levenshtein distance between strings a and b."""
        a, b = a.lower(), b.lower()
        m, n = len(a), len(b)
        if m == 0: return n
        if n == 0: return m
    
        # Initialize 2-row matrix to save space
        prev_row = list(range(n + 1))
        for i, ca in enumerate(a, start=1):
            curr_row = [i] + [0] * n
            for j, cb in enumerate(b, start=1):
                insert_cost = curr_row[j - 1] + 1
                delete_cost = prev_row[j] + 1
                replace_cost = prev_row[j - 1] + (ca != cb)
                curr_row[j] = min(insert_cost, delete_cost, replace_cost)
            prev_row = curr_row
        return prev_row[-1]
    
    
    # Predefined questions and answers
    responses = {
        "hello": "Hi there!",
        "hi": "Hello!",
        "what is your name": "I'm a simple chatbot.",
        "how are you": "I'm just code, but I'm doing fine!",
        "what can you do": "I can chat with you using simple matching.",
    }
    
    def get_response(user_query: str, threshold: float = 0.5) -> str:
        """
        Find the response whose question has the lowest Levenshtein distance
        to user_query. If similarity is below threshold, return default.
        """
        best_key = None
        best_dist = None
        for key in responses:
            dist = levenshtein(user_query, key)
            if best_dist is None or dist < best_dist:
                best_dist = dist
                best_key = key
    
        # Compute a simple similarity score: 1 - normalized distance
        # Normalization by the length of the longer string
        max_len = max(len(user_query), len(best_key))
        similarity = 1.0 - best_dist / max_len if max_len else 0.0
    
        if similarity < threshold:
            return "I don't understand."
        else:
            return responses[best_key]
    
    
    # Example usage
    if __name__ == "__main__":
        print("Type 'quit' to exit.")
        while True:
            user_input = input("> ")
            if user_input.strip().lower() == "quit":
                break
            print(get_response(user_input))
    
    • The levenshtein function computes the edit distance between two strings.
    • get_response finds the predefined question with the smallest distance to the user’s query, then calculates a simple similarity score by normalizing distance to the length of the longer string. If the similarity is below threshold, it returns the fallback "I don't understand.".
    • You can adjust the threshold (e.g., 0.5 → 50% similarity) and the responses dictionary to match your needs.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.