battle programmers alliance
Would you like to react to this message? Create an account in a few clicks or log in to continue.

battle programmers allianceLog in

the LivinGrimoire Artificial General Intelligence software design pattern forum

descriptiona blast from the past the legendary Eliza class! (python) Emptya blast from the past the legendary Eliza class! (python)

more_horiz
The Eliza chatbot class is a remarkable piece of engineering that has significantly contributed to the field of Natural Language Processing (NLP) and Artificial Intelligence (AI). This class, inspired by the original Eliza computer program developed at MIT, is a powerful tool for speech analysis and understanding conversational context.

One of the standout features of the Eliza class is its ability to elegantly request more data on a subject. It can guide a conversation in a way that feels natural and intuitive, encouraging users to provide more information without feeling overwhelmed or interrogated.

The Eliza class also excels at extracting parameters from strings. It uses regular expressions to identify and capture key pieces of information from a user’s input. This allows it to respond in a way that is specific and relevant to the user’s statements, enhancing the overall user experience.

Understanding conversational context is another area where the Eliza class shines. It can keep track of the flow of a conversation, allowing it to provide responses that are not only relevant to the user’s most recent statement, but also consistent with previous exchanges. This ability to maintain context is crucial for creating a chatbot that users can have meaningful and coherent conversations with.

In the world of AI, the Eliza class is a powerful tool for speech analysis. It can analyze user input to understand the intent behind it, enabling it to provide appropriate and accurate responses. This makes it an invaluable tool for developing chatbots that can interact with users in a way that feels natural and engaging.

The potential that the Eliza class brings to the world of AI is immense. It serves as a solid foundation for developing sophisticated chatbots capable of carrying out complex tasks. From customer service to mental health support, the applications are vast and varied.

In conclusion, the Eliza chatbot class is a testament to the power of AI and NLP. It encapsulates the principles of intelligent conversation handling, parameter extraction, and context understanding, making it a pivotal tool in the realm of AI-driven communication. The future of AI looks promising, and the Eliza class is undoubtedly playing a significant role in shaping it.  cyberpunk40x40

Code:


class Eliza:
    reflections = {
        "am": "are",
        "was": "were",
        "i": "you",
        "i'd": "you would",
        "i've": "you have",
        "my": "your",
        "are": "am",
        "you've": "I have",
        "you'll": "I will",
        "your": "my",
        "yours": "mine",
        "you": "i",
        "me": "you"
    }

    class PhraseMatcher:
        def __init__(self, matcher, responses):
            self.matcher = re.compile(matcher)
            self.responses = responses
            self.context: str = ""  # last speech context (subject or pattern)
            # example: i need (.*)
            self.param: str = ""  # last param extracted
            # example : water (for input: i need water)
            self.infoRequest: str = ""  # request more info on input
            # example: Why do you need {0}

        def matches(self, str):
            return self.matcher.match(str) is not None

        def respond(self, str):
            m = self.matcher.match(str)
            self.context = self.matcher.pattern  # context
            p = self.random_phrase()
            for i in range(len(m.groups())):
                s = self.reflect(m.group(i + 1))
                self.param = s  # param
                self.infoRequest = p  # more info request
                p = p.replace("{" + f'{i}' + "}", s)
            return p

        @staticmethod
        def reflect(s):
            words = s.split(" ")
            for i in range(len(words)):
                if words[i] in Eliza.reflections:
                    words[i] = Eliza.reflections[words[i]]
            return " ".join(words)

        def random_phrase(self):
            return self.responses[abs(random.randint(0, len(self.responses) - 1))]

        def __str__(self):
            return self.matcher.pattern + ":" + str(self.responses)

    babble = [
        PhraseMatcher("i need (.*)", ["Why do you need {0}?",
                                      "Would it really help you to get {0}?",
                                      "Are you sure you need {0}?"])
    ]
    babble.insert(len(babble), PhraseMatcher("why don'?t you ([^\\?]*)\\??", ["Do you really think I don't {0}?",
                                                        "Perhaps eventually I will {0}.",
                                                        "Do you really want me to {0}?"]))

    def respond(self, msg):
        for pm in self.babble:
            if pm.matches(msg):
                return pm.respond(msg.lower())
        return ""


Last edited by Admin on Mon Jan 15, 2024 9:46 pm; edited 1 time in total

descriptiona blast from the past the legendary Eliza class! (python) EmptyRe: a blast from the past the legendary Eliza class! (python)

more_horiz
the code is Python BTW

descriptiona blast from the past the legendary Eliza class! (python) Emptyswift ver Eliza

more_horiz
Swift ver:

Code:


class Eliza {
    static let reflections = [
        "am": "are",
        "was": "were",
        "i": "you",
        "i'd": "you would",
        "i've": "you have",
        "my": "your",
        "are": "am",
        "you've": "I have",
        "you'll": "I will",
        "your": "my",
        "yours": "mine",
        "you": "i",
        "me": "you"
    ]

    class PhraseMatcher {
        let matcher: NSRegularExpression
        let responses: [String]
        var context: String = ""  // last speech context (subject or pattern)
        var param: String = ""  // last param extracted
        var infoRequest: String = ""  // request more info on input

        init(matcher: String, responses: [String]) {
            self.matcher = try! NSRegularExpression(pattern: matcher, options: [])
            self.responses = responses
        }

        func matches(_ str: String) -> Bool {
            let range = NSRange(location: 0, length: str.utf16.count)
            return matcher.firstMatch(in: str, options: [], range: range) != nil
        }

        func respond(_ str: String) -> String {
            let range = NSRange(location: 0, length: str.utf16.count)
            guard let m = matcher.firstMatch(in: str, options: [], range: range) else { return "" }
            context = matcher.pattern  // context
            var p = randomPhrase()
            for i in 0..<m.numberOfRanges {
                let s = reflect(getParam(string2: str, string1: context))
                param = s  // param
                infoRequest = p  // more info request
                p = p.replacingOccurrences(of: "{\(i)}", with: s)
            }
            return p
        }
        func getParam(string2:String,string1:String) -> String {

            let words1 = string1.split(separator: " ").map(String.init)
            let words2 = string2.split(separator: " ").map(String.init)

            let difference = words2.filter { !words1.contains($0) }
            let differenceAsString = difference.joined(separator: " ")
            return differenceAsString
        }
        func reflect(_ s: String) -> String {
            var words = s.split(separator: " ")
            for i in 0..<words.count {
                if let reflection = Eliza.reflections[String(words[i])] {
                    words[i] = Substring(reflection)
                }
            }
            return words.joined(separator: " ")
        }

        func randomPhrase() -> String {
            return responses[Int.random(in: 0..<responses.count)]
        }

        var description: String {
            return "\(matcher.pattern): \(responses)"
        }
    }

    var babble = [
        PhraseMatcher(matcher: "i need (.*)", responses: ["Why do you need {0}?",
                                                          "Would it really help you to get {0}?",
                                                          "Are you sure you need {0}?"])
    ]

    func respond(_ msg: String) -> String {
        for pm in babble {
            if pm.matches(msg) {
                return pm.respond(msg.lowercased())
            }
        }
        return ""
    }
}
privacy_tip Permissions in this forum:
You cannot reply to topics in this forum
power_settings_newLogin to reply