AI-driven Chatbot Python, Java

👤 Sharing: AI
```python
import json
import random

class Chatbot:
    def __init__(self, knowledge_base_path="knowledge_base.json"):
        """
        Initializes the Chatbot with a knowledge base.

        Args:
            knowledge_base_path (str, optional): Path to the JSON knowledge base file. Defaults to "knowledge_base.json".
        """
        self.knowledge_base = self.load_knowledge_base(knowledge_base_path)

    def load_knowledge_base(self, path):
        """
        Loads the knowledge base from a JSON file.

        Args:
            path (str): The path to the JSON file.

        Returns:
            dict: The loaded knowledge base as a dictionary. Returns an empty dictionary if loading fails.
        """
        try:
            with open(path, 'r') as file:
                return json.load(file)
        except FileNotFoundError:
            print(f"Error: Knowledge base file not found at {path}.  Using an empty knowledge base.")
            return {}
        except json.JSONDecodeError:
            print(f"Error:  Invalid JSON format in {path}. Using an empty knowledge base.")
            return {}

    def save_knowledge_base(self, path="knowledge_base.json"):
        """
        Saves the current knowledge base to a JSON file.

        Args:
            path (str, optional): The path to save the file to. Defaults to "knowledge_base.json".
        """
        try:
            with open(path, 'w') as file:
                json.dump(self.knowledge_base, file, indent=4)
            print(f"Knowledge base saved to {path}")
        except Exception as e:
            print(f"Error saving knowledge base: {e}")


    def find_best_match(self, user_input):
        """
        Finds the best matching question in the knowledge base.

        Args:
            user_input (str): The user's input.

        Returns:
            str: The best matching question from the knowledge base, or None if no good match is found.
        """
        best_match = None
        best_similarity = 0  # Using a simple similarity measure for now

        for question in self.knowledge_base:
            similarity = self.calculate_similarity(user_input, question)
            if similarity > best_similarity:
                best_similarity = similarity
                best_match = question

        if best_similarity > 0.6: #Adjust threshold as needed
            return best_match
        else:
            return None # No good match found

    def calculate_similarity(self, user_input, known_question):
        """
        Calculates a simple similarity score between two strings.
        This is a basic implementation and can be improved.

        Args:
            user_input (str): The user's input string.
            known_question (str): A question from the knowledge base.

        Returns:
            float: A similarity score between 0 and 1.
        """
        user_input = user_input.lower()
        known_question = known_question.lower()

        words_in_input = set(user_input.split())
        words_in_question = set(known_question.split())

        common_words = words_in_input.intersection(words_in_question)
        union_words = words_in_input.union(words_in_question)

        if not union_words:
            return 0.0  # Avoid division by zero

        return len(common_words) / len(union_words)


    def get_answer(self, question):
        """
        Retrieves the answer to a given question from the knowledge base.

        Args:
            question (str): The question to answer.

        Returns:
            str: The answer to the question, or a default message if the question is not found.
        """
        return self.knowledge_base.get(question, "I don't know the answer to that question.  Please try rephrasing or add it to the knowledge base.")


    def train(self, question, answer):
        """
        Adds a new question and answer to the knowledge base.

        Args:
            question (str): The question to add.
            answer (str): The answer to the question.
        """
        self.knowledge_base[question] = answer
        self.save_knowledge_base()
        print("Training complete.")

    def chat(self):
        """
        Starts the chatbot interaction loop.
        """
        print("Chat with me! (type 'quit' to exit, 'train' to teach me something)")
        while True:
            user_input = input("You: ")

            if user_input.lower() == 'quit':
                break
            elif user_input.lower() == 'train':
                question = input("Enter the question: ")
                answer = input("Enter the answer: ")
                self.train(question, answer)
            else:
                best_match = self.find_best_match(user_input)

                if best_match:
                    answer = self.get_answer(best_match)
                    print("Chatbot:", answer)
                else:
                    print("Chatbot: I don't know the answer to that.  Would you like to train me? (yes/no)")
                    train_response = input("You: ").lower()
                    if train_response == 'yes':
                        question = user_input
                        answer = input("Enter the answer: ")
                        self.train(question, answer)
                    else:
                        print("Chatbot: Okay, I'll wait for further instructions.")



# Example Usage
if __name__ == "__main__":
    # Create a simple knowledge base file if one doesn't exist.
    try:
        with open("knowledge_base.json", "x") as f:
            json.dump({}, f)
    except FileExistsError:
        pass # File already exists, no need to create it


    chatbot = Chatbot()
    chatbot.chat()
```
```java
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import org.json.JSONObject;
import org.json.JSONTokener;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;


public class Chatbot {

    private Map<String, String> knowledgeBase;
    private String knowledgeBaseFilePath = "knowledge_base.json"; // Default path

    public Chatbot() {
        this.knowledgeBase = loadKnowledgeBase(knowledgeBaseFilePath);
    }

    public Chatbot(String knowledgeBaseFilePath) {
        this.knowledgeBaseFilePath = knowledgeBaseFilePath;
        this.knowledgeBase = loadKnowledgeBase(knowledgeBaseFilePath);
    }

    private Map<String, String> loadKnowledgeBase(String path) {
        Map<String, String> kb = new HashMap<>();
        try (FileReader reader = new FileReader(path)) {
            JSONTokener tokener = new JSONTokener(reader);
            JSONObject jsonObject = new JSONObject(tokener);

            jsonObject.keySet().forEach(key -> {
                kb.put(key, jsonObject.getString(key));
            });

        } catch (IOException e) {
            System.err.println("Error loading knowledge base from " + path + ": " + e.getMessage());
            System.err.println("Using an empty knowledge base.");
            return new HashMap<>();
        } catch (org.json.JSONException e) {
            System.err.println("Error parsing JSON from " + path + ": " + e.getMessage());
            System.err.println("Using an empty knowledge base.");
            return new HashMap<>();
        }
        return kb;
    }

    public void saveKnowledgeBase() {
        saveKnowledgeBase(knowledgeBaseFilePath);
    }

    public void saveKnowledgeBase(String path) {
        JSONObject jsonObject = new JSONObject(knowledgeBase);

        try (FileWriter writer = new FileWriter(path)) {
            writer.write(jsonObject.toString(4)); // Use toString(4) for pretty printing
            System.out.println("Knowledge base saved to " + path);
        } catch (IOException e) {
            System.err.println("Error saving knowledge base to " + path + ": " + e.getMessage());
        }
    }

    public String findBestMatch(String userInput) {
        String bestMatch = null;
        double bestSimilarity = 0;

        for (String question : knowledgeBase.keySet()) {
            double similarity = calculateSimilarity(userInput, question);
            if (similarity > bestSimilarity) {
                bestSimilarity = similarity;
                bestMatch = question;
            }
        }

        if (bestSimilarity > 0.6) { // Adjust threshold as needed
            return bestMatch;
        } else {
            return null; // No good match found
        }
    }

    private double calculateSimilarity(String userInput, String knownQuestion) {
        userInput = userInput.toLowerCase();
        knownQuestion = knownQuestion.toLowerCase();

        String[] userInputWords = userInput.split("\\s+");
        String[] knownQuestionWords = knownQuestion.split("\\s+");

        int commonWords = 0;
        for (String word : userInputWords) {
            for (String knownWord : knownQuestionWords) {
                if (word.equals(knownWord)) {
                    commonWords++;
                    break; // To avoid double counting if a word appears multiple times
                }
            }
        }

        //Jaccard Index:  common / (total in both)
        int totalWords = userInputWords.length + knownQuestionWords.length - commonWords;

        if (totalWords == 0) {
            return 0.0; // Avoid division by zero
        }

        return (double) commonWords / totalWords;
    }

    public String getAnswer(String question) {
        return knowledgeBase.getOrDefault(question, "I don't know the answer to that question. Please try rephrasing or add it to the knowledge base.");
    }

    public void train(String question, String answer) {
        knowledgeBase.put(question, answer);
        saveKnowledgeBase();
        System.out.println("Training complete.");
    }

    public void chat() {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Chat with me! (type 'quit' to exit, 'train' to teach me something)");

        while (true) {
            System.out.print("You: ");
            String userInput = scanner.nextLine();

            if (userInput.equalsIgnoreCase("quit")) {
                break;
            } else if (userInput.equalsIgnoreCase("train")) {
                System.out.print("Enter the question: ");
                String question = scanner.nextLine();
                System.out.print("Enter the answer: ");
                String answer = scanner.nextLine();
                train(question, answer);
            } else {
                String bestMatch = findBestMatch(userInput);

                if (bestMatch != null) {
                    String answer = getAnswer(bestMatch);
                    System.out.println("Chatbot: " + answer);
                } else {
                    System.out.println("Chatbot: I don't know the answer to that. Would you like to train me? (yes/no)");
                    String trainResponse = scanner.nextLine().toLowerCase();
                    if (trainResponse.equals("yes")) {
                        System.out.print("Enter the question: ");
                        String question = userInput;
                        System.out.print("Enter the answer: ");
                        String answer = scanner.nextLine();
                        train(question, answer);
                    } else {
                        System.out.println("Chatbot: Okay, I'll wait for further instructions.");
                    }
                }
            }
        }

        scanner.close();
    }

    public static void main(String[] args) {
        // Create a simple knowledge base file if one doesn't exist.
        java.io.File file = new java.io.File("knowledge_base.json");
        if (!file.exists()) {
            try (FileWriter writer = new FileWriter("knowledge_base.json")) {
                writer.write("{}"); // Write an empty JSON object
            } catch (IOException e) {
                System.err.println("Failed to create initial knowledge_base.json: " + e.getMessage());
            }
        }
        Chatbot chatbot = new Chatbot();
        chatbot.chat();
    }
}
```
👁️ Viewed: 20

Comments