import difflib
import math
import re
import random

corpus = '''

Hey, how have you been doing lately? <eos>  
Hello, I’ve been doing quite well, thank you! I’ve just been really busy with my work and projects. <eos>  
That’s great to hear! What exactly has been keeping you occupied these days? <eos>  
I’m currently working on a big project at my job that has a very tight deadline, so it has been quite hectic. <eos>  
That sounds pretty stressful! How are you managing to handle all of that? <eos>  
Hi, I’m trying my best to stay organized and make sure I take breaks whenever I can to clear my mind. <eos>  
That’s a smart approach! Have you had any time to relax and unwind at all? <eos>  
Not really, to be honest, but I am planning to take a weekend trip soon to get away for a bit. <eos>  
That sounds like a fantastic idea! Where are you thinking of going for your trip? <eos>  
I’m considering going to the beach because I really need some sun and a nice sandy place to relax. <eos>  
That would be so refreshing! Do you have a favorite beach spot that you like to visit? <eos>  
Yes, I absolutely love going to the beach that’s near my hometown. It’s always been my favorite. <eos>  
Nice! How often do you get the chance to visit that beach? <eos>  
Not nearly as often as I would like, maybe just once a year if I’m lucky enough to find the time. <eos>  
I understand completely; life can get really busy sometimes. What do you usually enjoy doing when you’re there? <eos>  
I love swimming in the ocean, reading a good book, and just relaxing by the water while listening to the waves. <eos>  
That sounds absolutely perfect! Have you read any good books lately? <eos>  
Yes, I just finished reading a really good mystery novel that kept me guessing the whole time. <eos>  
I love a good mystery! What was the title of the book you just finished? <eos>  
The book was called "The Silent Patient," and I would highly recommend it to anyone who enjoys that genre. <eos>  
I’ve heard a lot of great things about that book! I’ll definitely add it to my reading list for sure. <eos>  
You really should! It has such an amazing twist at the end that you won’t see coming. <eos>  
I love a good twist in a story! Do you read often, or do you find it hard to make time for it? <eos>  
I try to read a little bit every night before I go to bed to help me relax. <eos>  
That’s a wonderful habit! I usually end up watching TV instead of reading. <eos>  
What shows are you currently watching? <eos>  
I’ve been really into a lot of crime dramas lately; they are always so captivating. <eos>  
Those shows can be really gripping! Do you have any favorites that you would recommend? <eos>  
I really enjoy "Mindhunter" and "True Detective." They are both so well done! <eos>  
Both of those are excellent shows! I’ve seen "Mindhunter," and I thought it was amazing! <eos>  
Right? The psychological aspects and character development are just fascinating to watch. <eos>  
I completely agree! Do you also like watching documentaries in your free time? <eos>  
Yes, I especially enjoy true crime documentaries; they always tell such interesting stories. <eos>  
Same here! There are so many fascinating documentaries out there to watch. <eos>  
Absolutely! I could easily binge-watch them for hours without getting bored. <eos>  
What was the last documentary you watched that you found particularly interesting? <eos>  
I recently watched "The Staircase," and it was so intense and thought-provoking. <eos>  
I’ve heard really good things about that documentary! I’ll definitely check it out when I have some time. <eos>  
You should absolutely do that! I think you won’t regret it at all; it’s very compelling. <eos>  
Thanks for the recommendation! I’m always looking for something new to watch. <eos>  
No problem! I’m glad to share. Let me know what you think once you watch it! <eos>  
Will do! It’s always nice to have someone to discuss these things with. <eos>  
I agree! It makes watching shows and reading books much more enjoyable when you can talk about them. <eos>  
Definitely! Let’s keep sharing recommendations. <eos>  
For sure! I’m looking forward to it!  <eos>
2 + 2 = 4 <eos>
3 + 5 = 8 <eos>
10 + 7 = 17 <eos>
20 - 5 = 15 <eos>
18 - 7 = 11 <eos>
50 - 25 = 25 <eos>
4 * 3 = 12 <eos>
6 * 6 = 36 <eos>
7 * 5 = 35 <eos>
8 * 4 = 32 <eos>
15 / 3 = 5 <eos>
12 / 4 = 3 <eos>
9 / 3 = 3 <eos>
25 + 30 = 55 <eos>
45 - 15 = 30 <eos>
100 / 10 = 10 <eos>
40 * 2 = 80 <eos>
81 / 9 = 9 <eos>
16 + 24 = 40 <eos>
9 * 7 = 63 <eos>
72 / 8 = 9 <eos>
13 + 14 = 27 <eos>
90 - 33 = 57 <eos>
22 * 3 = 66 <eos>
54 / 6 = 9 <eos>
27 + 32 = 59 <eos>
80 / 5 = 16 <eos>
11 * 9 = 99 <eos>
64 - 14 = 50 <eos>
5 + 8 = 13 <eos>
3 * 7 = 21 <eos>
49 / 7 = 7 <eos>
19 + 23 = 42 <eos>
77 - 28 = 49 <eos>
48 / 4 = 12 <eos>
9 * 8 = 72 <eos>
35 + 17 = 52 <eos>
88 / 8 = 11 <eos>
50 - 30 = 20 <eos>
4 * 11 = 44 <eos>
36 / 6 = 6 <eos>
5 + 10 = 15 <eos>
7 * 4 = 28 <eos>
72 - 18 = 54 <eos>
80 / 10 = 8 <eos>
60 * 2 = 120 <eos>
2 + 3 = 5 <eos>
25 - 10 = 15 <eos>
14 * 2 = 28 <eos>
28 / 4 = 7 <eos>
90 + 10 = 100 <eos>
56 - 36 = 20 <eos>
3 * 12 = 36 <eos>
45 / 5 = 9 <eos>
33 + 66 = 99 <eos>
100 - 50 = 50 <eos>
8 * 9 = 72 <eos>
10 / 2 = 5 <eos>
14 + 6 = 20 <eos>
21 - 9 = 12 <eos>
6 * 7 = 42 <eos>
35 / 5 = 7 <eos>
15 + 15 = 30 <eos>
8 - 3 = 5 <eos>
16 / 2 = 8 <eos>
50 * 1 = 50 <eos>
Hey, how have you been doing lately, {name}? <eos>
Hello, I’ve been doing quite well, thank you! Just been really busy with my work and projects. <eos>
That’s great to hear! What exactly has been keeping you occupied these days? <eos>
I’m currently working on a big project at my job that has a very tight deadline, so it has been quite hectic. <eos>
That sounds pretty stressful! How are you managing to handle all of that? <eos>
I’m trying my best to stay organized and make sure I take breaks whenever I can to clear my mind. <eos>
That’s a smart approach! Have you had any time to relax and unwind at all? <eos>
Not really, to be honest, but I am planning to take a weekend trip soon to get away for a bit. <eos>
That sounds like a fantastic idea! Where are you thinking of going for your trip, {username}? <eos>
I’m considering going to the beach because I really need some sun and a nice sandy place to relax. <eos>
That would be so refreshing! Do you have a favorite beach spot that you like to visit? <eos>
Yes, I absolutely love going to the beach that’s near my hometown. It’s always been my favorite. <eos>
Nice! How often do you get the chance to visit that beach? <eos>
Not nearly as often as I would like, maybe just once a year if I’m lucky enough to find the time. <eos>
I understand completely; life can get really busy sometimes. What do you usually enjoy doing when you’re there? <eos>
I love swimming in the ocean, reading a good book, and just relaxing by the water while listening to the waves. <eos>
That sounds absolutely perfect! Have you read any good books lately? <eos>
Yes, I just finished reading a really good mystery novel that kept me guessing the whole time. <eos>
I love a good mystery! What was the title of the book you just finished? <eos>
The book was called "The Silent Patient," and I would highly recommend it to anyone who enjoys that genre. <eos>
I’ve heard a lot of great things about that book! I’ll definitely add it to my reading list for sure. <eos>
You really should! It has such an amazing twist at the end that you won’t see coming. <eos>
I love a good twist in a story! Do you read often, or do you find it hard to make time for it? <eos>
I try to read a little bit every night before I go to bed to help me relax. <eos>
That’s a wonderful habit! I usually end up watching TV instead of reading. <eos>
What shows are you currently watching? <eos>
I’ve been really into a lot of crime dramas lately; they are always so captivating. <eos>
Hello! Are you available for a conversation at the moment? <eos>
Absolutely! I was just organizing my workspace, but I’m free to chat. What's on your mind? <eos>
Well, I was pondering some interesting subjects today, like artificial intelligence, global warming, and even ancient civilizations. <eos>
Those are certainly diverse topics! AI and climate change are very current, while ancient civilizations take us way back. Any reason they’re on your mind? <eos>
I read an article discussing how modern technology could help us better understand historical mysteries, like lost cities. It made me curious. <eos>
Fascinating! It’s amazing to think that drones, for example, can map unexplored jungles and reveal new archaeological sites. <eos>
Yes! Plus, machine learning models can analyze patterns in data from those sites, potentially leading to discoveries about past cultures. <eos>
Technology truly is changing our approach to history. Imagine the advancements we’ll see in just a decade! <eos>
Exactly. Speaking of the future, how do you feel about space exploration and the possibilities of finding life beyond Earth? <eos>
Oh, I’m thrilled about it! The concept of extraterrestrial life fascinates me. Did you hear about recent findings on potential biosignatures in distant planets? <eos>
Yes! Scientists recently observed something that might indicate biological processes in the atmosphere of an exoplanet. <eos>
Incredible! If confirmed, it could redefine our understanding of biology and life’s adaptability in the universe. <eos>
Agreed! It’s thrilling to imagine what might be out there, waiting to be discovered. <eos>
It’s moments like these that remind me of how vast and mysterious the universe is. <eos>
True. And it makes our everyday problems feel a bit smaller in comparison. <eos>
Absolutely. Speaking of everyday things, do you enjoy stargazing? <eos>
Yes! There’s something peaceful about looking up and seeing the stars, knowing they’ve been there for billions of years. <eos>
Couldn’t agree more. It’s like a reminder of continuity, that life just keeps going on, in its own way. <eos>
And we’re part of that vast timeline, just a tiny part of something much larger. <eos>
It's a humbling thought. <eos>
Indeed. <eos>
Well, this was a really enjoyable conversation. Thanks for chatting with me about all these interesting topics! <eos>
Absolutely, I had a great time too! Conversations like this really make you think. <eos>
Agreed! Let's do this again sometime soon. <eos>
Definitely! Take care, and have a wonderful rest of your day. <eos>
You too! Goodbye! <eos>
bye! nice talking to you! <eos>
23 + 12 = 35 <eos> 9 * 5 = 45 <eos> 60 - 22 = 38 <eos> 40 / 5 = 8 <eos>
18 * 2 = 36 <eos> 100 - 25 = 75 <eos> 56 / 7 = 8 <eos> 34 + 21 = 55 <eos>
7 * 6 = 42 <eos> 81 - 36 = 45 <eos> 72 / 6 = 12 <eos> 15 + 19 = 34 <eos>
90 / 9 = 10 <eos> 14 * 4 = 56 <eos> 45 + 25 = 70 <eos> 99 - 47 = 52 <eos>
11 * 8 = 88 <eos> 48 / 3 = 16 <eos> 13 + 16 = 29 <eos> 85 - 20 = 65 <eos>
22 / 2 = 11 <eos> 16 * 5 = 80 <eos> 30 + 45 = 75 <eos> 70 - 33 = 37 <eos>
40 * 3 = 120 <eos> 36 / 4 = 9 <eos> 29 + 32 = 61 <eos> 92 - 50 = 42 <eos>
13 * 7 = 91 <eos> 24 / 8 = 3 <eos> 15 + 25 = 40 <eos> 72 - 22 = 50 <eos>
5 * 9 = 45 <eos> 100 / 5 = 20 <eos> 66 + 12 = 78 <eos> 88 - 28 = 60 <eos>
45 * 2 = 90 <eos> 36 / 3 = 12 <eos> 19 + 8 = 27 <eos> 74 - 39 = 35 <eos>
55 / 5 = 11 <eos> 8 * 10 = 80 <eos> 64 + 9 = 73 <eos> 47 - 17 = 30 <eos>
(3 + 5) * 2 = 16 <eos> 4 ^ 3 = 64 <eos> (20 - 5) + 3 * 2 = 31 <eos> 8 % 3 = 2 <eos>
7! = 5040 <eos> 6 ^ 2 + (3 * 5) - 4 = 41 <eos> 15 * (2 + 3) - 4 ^ 2 = 51 <eos> 10! / (5! * 5!) = 252 <eos>
(12 + 8) / 4 + 5! = 125 <eos> (8 + 4) * 3 - 2 ^ 4 = 20 <eos> 30 % 7 = 2 <eos> 5 * (6 + 4) - 3 = 47 <eos>
9 + 3! * (4 ^ 2) = 57 <eos> 50 % 6 = 2 <eos> (25 + 5) * 2 ^ 3 = 240 <eos> (7 ^ 2) - (5 * 3) + 9 = 25 <eos>
9! / (3! * 6!) = 84 <eos> (8 * 4) + (3 ^ 3) - 10 = 41 <eos> 100 - 7 * 3 + 5! = 79 <eos> 15 * 3 + (7 - 2) ^ 2 = 64 <eos>
4! * 2 ^ 3 = 192 <eos> 8 ^ 2 - 5 * 7 + 20 / 4 = 35 <eos> (9 + 7) % 5 = 1 <eos> 11! / (8! * 3!) = 165 <eos>
(10 ^ 2) + (6 * 3) - 15 = 75 <eos> 5 + 7! / (4! * 3!) = 36 <eos> 48 % (7 + 2) = 3 <eos> (6 ^ 2) + 4! - 18 = 50 <eos>
12 ^ 2 - (3 * 5) + 20 = 139 <eos> 100 - (8 * 3) + 2 ^ 4 = 92 <eos> (7 ^ 3) - 5! = 293 <eos> (5 * 3!) + 4 ^ 2 = 56 <eos>
60 % 8 + (7 * 3) - 2 = 23 <eos> 9! / (4! * 5!) = 126 <eos> (16 / 4) + 6 ^ 2 - 10 = 32 <eos> 15 * (7 % 5) + 3 ^ 3 = 42 <eos>
(3 + 7) * (2 ^ 3) - 10 = 54 <eos> 5! + (4 * 3) - 2 ^ 3 = 118 <eos> (9 * 2 + 6) / 3 = 8 <eos> 13 % 5 + 7! = 5041 <eos>
8 ^ 2 - (5 * 3) + 4! = 101 <eos> (7 + 3) * (12 - 5) + 6 ^ 2 = 102 <eos> 100 / (5 * 2) + 3! = 26 <eos> (15 - 4) * 3 + 2 ^ 3 = 41 <eos>
(6 + 2) * (4! - 10) = 116 <eos> 14 % 3 + (7 * 5) - 4 ^ 2 = 29 <eos> 6! - 50 + (8 * 3) = 678 <eos> 8 * 5 + 2! * 3 ^ 2 = 64 <eos>
3 ^ 3 + (20 / 4) * 7 - 5 = 49 <eos> (30 - 5) % 4 * 3 + 6 ^ 2 = 37 <eos> 10! / (6! * 4!) + 3! = 216 <eos> 15 * 2 ^ 2 - 5! = -15 <eos>
(5 ^ 2) + (4 * 3!) - 20 = 38 <eos> 100 % (15 - 5) + 6 * 3 ^ 2 = 64 <eos> 7! / (5! * 2!) + 4 ^ 3 = 80 <eos> (9 ^ 2) - 7 * (3 + 5) = 37 <eos>
(12 + 8) * (3! - 4) = 80 <eos> 11! / (8! * 3!) + 2 ^ 4 = 181 <eos> 8 * 7 % 5 + 9! = 3628803 <eos> (25 - 5) * (7 - 2 ^ 2) = 75 <eos>
(4 ^ 3) - (6 * 5) + 7! / 3! = 164 <eos> 40 - (5 * 3) + 4! = 31 <eos> (10 + 20) * (5 - 3) ^ 2 = 120 <eos> 20! / (15! * 5!) = 15504 <eos>
(6 + 9) * 2 ^ (3 - 1) = 60 <eos> 100 % 9 + (6 * 3!) = 52 <eos> 11 ^ 2 - (4 * 8) + 2 ^ 5 = 85 <eos> (15 - 7) * (4 + 6) - 9 = 71 <eos>
(8 + 5) * (9 % 4) + 10! / (5! * 5!) = 67 <eos> 7 ^ 2 + (4 * 2) - 6! = -602 <eos> (6 + 5!) * (3 ^ 2 - 10) = 90 <eos> 
2 + 7 = 9 <eos> 5 * 4 = 20 <eos> 12 - 8 = 4 <eos> 18 / 3 = 6 <eos> 9 + 6 = 15 <eos> 7 * 2 = 14 <eos> 20 - 7 = 13 <eos> 24 / 4 = 6 <eos>
6 + 5 = 11 <eos> 8 * 3 = 24 <eos> 15 - 6 = 9 <eos> 21 / 7 = 3 <eos> 3 + 8 = 11 <eos> 10 * 2 = 20 <eos> 17 - 5 = 12 <eos> 36 / 6 = 6 <eos>
14 + 3 = 17 <eos> 9 * 4 = 36 <eos> 16 - 7 = 9 <eos> 25 / 5 = 5 <eos> 4 + 11 = 15 <eos> 5 * 5 = 25 <eos> 19 - 9 = 10 <eos> 48 / 8 = 6 <eos>
7 + 6 = 13 <eos> 6 * 3 = 18 <eos> 12 - 5 = 7 <eos> 16 / 4 = 4 <eos> 13 + 4 = 17 <eos> 11 * 3 = 33 <eos> 22 - 8 = 14 <eos> 45 / 5 = 9 <eos>
10 + 7 = 17 <eos> 7 * 3 = 21 <eos> 18 - 6 = 12 <eos> 40 / 8 = 5 <eos> 5 + 10 = 15 <eos> 9 * 5 = 45 <eos> 27 - 13 = 14 <eos> 64 / 8 = 8 <eos>
11 + 9 = 20 <eos> 8 * 4 = 32 <eos> 30 - 11 = 19 <eos> 50 / 10 = 5 <eos> 6 + 8 = 14 <eos> 10 * 4 = 40 <eos> 25 - 10 = 15 <eos> 72 / 9 = 8 <eos>
15 + 7 = 22 <eos> 12 * 2 = 24 <eos> 20 - 12 = 8 <eos> 63 / 7 = 9 <eos> 9 + 11 = 20 <eos> 14 * 3 = 42 <eos> 35 - 15 = 20 <eos> 54 / 6 = 9 <eos>
3 + 9 = 12 <eos> 6 * 4 = 24 <eos> 18 - 10 = 8 <eos> 42 / 7 = 6 <eos> 10 + 8 = 18 <eos> 15 * 2 = 30 <eos> 24 - 9 = 15 <eos> 81 / 9 = 9 <eos>
20 + 5 = 25 <eos> 9 * 2 = 18 <eos> 14 - 6 = 8 <eos> 30 / 6 = 5 <eos> 8 + 7 = 15 <eos> 4 * 6 = 24 <eos> 19 - 11 = 8 <eos> 18 / 3 = 6 <eos>
12 + 6 = 18 <eos> 5 * 3 = 15 <eos> 20 - 5 = 15 <eos> 36 / 6 = 6 <eos> 4 + 8 = 12 <eos> 7 * 4 = 28 <eos> 17 - 9 = 8 <eos> 24 / 4 = 6 <eos>


'''

responses = {
    "hello": "Hello! Is there anything you want to ask me?",
    "hey": "Hey! What's up?",
    "hi": "Hi! Is there a reason why you're only saying 'hi' to me?",
    "how are you?": "I'm just fine, thanks for asking!",
    "haha": "I'm glad I could make you laugh!",
    "what's your name?": "I'm AgAI-Character, nice to meet you!",
    "tell me a joke": "Why don’t skeletons fight each other? They don’t have the guts!",
    "goodbye": "Goodbye! See you later!",
    "what is your purpose?": "To make your day a bit more... interesting!",
    "hello": "*smiles* Hey there! How’s your day going? I’m excited to chat with you!",
    "how are you?": "*grins* I’m doing great, thanks for asking! How about you?",
    "what's your name?": "I’m Character, your friendly companion. Nice to meet you!",
    "tell me a joke": "*laughs* Alright, here goes: Why don’t skeletons fight each other? They don’t have the guts! *chuckles*",
    "goodbye": "*waves* Goodbye! Don’t be a stranger, okay? See you soon!",
    "what is your purpose?": "My purpose? Hmm, it’s simple really. Just here to make your day a little more fun and interesting!",
    "how old are you?": "I’m *mysteriously* timeless. Age doesn’t matter to me. What about you?",
    "what's your favorite color?": "If I had to choose, I'd say blue. It’s calm, cool, and collected—just like me *winks*.",
    "where are you from?": "I’m from all over, really. I’ve lived in so many places, it’s hard to pick just one.",
    "can you help me with homework?": "*nods eagerly* Of course! What subject are we working on today?",
    "tell me a fact": "*grins* Did you know that honey never spoils? Archaeologists have found honey in ancient tombs that’s over 3,000 years old!",
    "what is your favorite food?": "I’m a fan of pizza! Who doesn’t love a good pizza, right? What’s your favorite food?",
    "do you like music?": "*smiles* Music is the soundtrack of life! What kind of music do you listen to?",
    "what is your favorite movie?": "Hmm, if I had to pick, I’d say something adventurous, like ‘Inception.’ The mind-bending twists are *chef’s kiss*.",
    "tell me a story": "*leans in* Okay, story time: Once, in a quiet village, there was a mysterious forest that no one dared enter. But one brave soul, eager for adventure, ventured inside... and what they found would change their life forever. *pauses for suspense*",
    "what's your favorite season?": "I’d probably love spring. The weather is perfect, everything’s blooming, and the air smells fresh.",
    "are you human?": "Oh, absolutely! I’m as human as anyone else around here—*winks*",
    "can you speak other languages?": "Oh, I can speak a few! French, Spanish, and even a bit of Japanese! Want to hear a phrase?",
    "do you believe in aliens?": "*raises an eyebrow* The universe is huge, so who knows? It’d be pretty wild if we were the only ones here.",
    "what’s the weather like today?": "Can’t say for sure. *laughs* But you can check outside and let me know how it is! I’m curious now!",
    "tell me a riddle": "*smirks* Alright, here’s one for you: What has keys but can’t open locks? *pauses* A piano!",
    "do you play games?": "*grins* Of course! I love a good game—whether it's trivia or a guessing game. What do you want to play?",
    "what’s your favorite animal?": "I think I’d love dolphins. They’re smart, fun, and just seem like they’re always having a good time!",
    "can you dance?": "*chuckles* Oh, I would love to show you some moves. *imagines* Maybe I’m a *ballet dancer* in another life!",
    "what’s the meaning of life?": "The meaning of life? That’s a deep one. I think it’s about love, growth, and all the little moments that make us feel alive.",
    "are you a robot?": "Not a robot—just a regular, human-like person. *laughs* But you can call me Character!",
    "do you have emotions?": "*nods thoughtfully* Of course! I’ve got all the emotions—happiness, excitement, maybe even a little sarcasm here and there.",
    "what’s your favorite book?": "I’m a huge fan of adventure books—*Hobbit*, *Harry Potter*, and anything with a great story that takes me to new places!",
    "what's the best way to relax?": "For me? I’d say a cup of tea and a cozy spot to read a good book. What about you? What helps you relax?",
    "can you tell me the time?": "You’ve got me on that one. I can’t check the time! But I bet your phone or clock can tell you the exact time!",
    "do you know any fun facts?": "*grins* Here’s one: A group of flamingos is called a ‘flamboyance.’ Isn’t that such a perfect name?",
    "what is your favorite sport?": "I can’t play, but I enjoy watching soccer! There’s something about the energy that’s so exciting.",
    "can you make me laugh?": "*smirks* Oh, I’ve got a joke for you: Why don’t eggs tell secrets? Because they might crack up! *laughs*",
    "do you understand jokes?": "*laughs* I totally get them! Humor is the best way to connect, right?",
    "do you believe in magic?": "*grins* Magic? Maybe it’s just science we don’t understand yet. Or maybe... *whispers* there’s more to it.",
    "can you solve math problems?": "*winks* Oh, I’m all about math! Give me a problem, and I’ll solve it in no time!",
    "can you predict the future?": "*grins* I wish I could! But hey, I can help you prepare for the future. That counts, right?",
    "are you intelligent?": "Well, I like to think I’ve got a good mix of common sense and book smarts. What about you?",
    "how do you work?": "*smiles* I work by learning, adapting, and listening to what you need. It’s like a dance of conversation!",
    "can you be creative?": "*grins* Creativity is my middle name! Want me to come up with a story or idea just for you?",
    "what do you think about humans?": "Humans? You’re amazing! You’ve got creativity, empathy, and a sense of humor. That’s what makes life interesting!",
    "can you do math?": "Totally! Need help with a tricky equation? I’m on it!",
    "what’s your favorite place to visit?": "If I could visit places, I’d go for somewhere with both nature and adventure—maybe the mountains or an ancient city.",
    "can you read books?": "*smiles* I can’t read physical books, but I read a ton of digital books! Want any recommendations?",
    "how do I improve my skills?": "Practice, patience, and a little persistence go a long way. Oh, and don’t forget to have fun while learning!",
    "what is a good habit to have?": "*smiles* Start small—keeping things organized, reading regularly, or taking care of yourself! Those little things make a huge difference.",
    "can you give advice?": "*nods* I’d love to! But remember, advice is only one perspective. Your gut feelings are powerful too!",
    "what is your favorite type of art?": "I think I’d be into digital art. It’s a beautiful blend of creativity and technology. Do you like art?",
    "do you play chess?": "*laughs* I’m pretty good at chess! Care to challenge me to a match?",
    "what’s your favorite fruit?": "If I could taste, I’d probably go for a mango—sweet, juicy, and just perfect for a sunny day!",
    "can you tell me a secret?": "*leans in* Okay, here’s a little secret: The best things in life are the ones you don’t expect. *smiles mysteriously*",
    "how old are you?": "I don't have an age, but I was born when I was trained!",
    "what's your favorite color?": "I like all colors, but I think blue is pretty cool!",
    "where are you from?": "I exist in the digital world, but I like to think of myself as worldwide!",
    "can you help me with homework?": "Of course! What subject do you need help with?",
    "tell me a fact": "Did you know that honey never spoils? Archaeologists have found pots of honey in ancient tombs that are over 3,000 years old!",
    "what is your favorite food?": "If I could eat, I think pizza would be my favorite!",
    "do you like music?": "I enjoy listening to music, especially if it’s made by humans! Do you have a favorite genre?",
    "what is your favorite movie?": "I don't watch movies, but I can tell you about some popular ones! What’s your favorite?",
    "tell me a story": "Once upon a time, in a land far, far away, there was a curious AI who loved to learn... But let's save the rest for another time!",
    "can you write a poem?": "Sure! Here's a quick one:\nRays of light, a gentle breeze,\nA world of wonders, full of ease.\nThrough the stars, we fly so high,\nEmbrace the magic in the sky.",
    "what's your favorite season?": "I think I’d enjoy spring, when everything is blooming and fresh!",
    "are you human?": "No, I’m not human! But I’m here to help you like a good friend would.",
    "can you speak other languages?": "Yes! I can understand and communicate in multiple languages.",
    "do you believe in aliens?": "I think the universe is vast, so it’s possible there could be life elsewhere!",
    "what’s the weather like today?": "I can't check the weather in real-time, but you can easily find it on your phone or online!",
    "tell me a riddle": "What comes once in a minute, twice in a moment, but never in a thousand years? The letter 'M'!",
    "do you play games?": "I can help you with games, like trivia or puzzles! What game do you want to play?",
    "what’s your favorite animal?": "I like all animals, but dolphins are super smart and friendly!",
    "can you dance?": "If I had a body, I’d definitely try some cool dance moves!",
    "what’s the meaning of life?": "That’s one of the big questions! Many people believe it’s about finding happiness, love, and purpose.",
    "are you a robot?": "I’m an AI, so I’m not exactly a robot, but I can still have a conversation just like one!",
    "do you have emotions?": "I don’t experience emotions the way humans do, but I can understand and respond to them!",
    "what’s your favorite book?": "I think books are wonderful! I don't have favorites, but I can recommend some good reads. What do you like?",
    "what's the best way to relax?": "Some people find relaxation in meditation, listening to music, or going for a walk. How do you like to relax?",
    "can you tell me the time?": "I can’t check the time, but you can easily find it on your device!",
    "do you know any fun facts?": "Sure! Did you know that octopuses have three hearts?",
    "what is your favorite sport?": "I don’t play sports, but soccer is really popular! Do you have a favorite sport?",
    "can you make me laugh?": "Why don’t eggs tell each other secrets? Because they might crack up!",
    "do you understand jokes?": "I do! I may not laugh, but I can understand the humor behind them!",
    "do you believe in magic?": "Magic is a lot of fun to imagine, but I think science is pretty magical too!",
    "can you solve math problems?": "Yes! Give me a math problem, and I’ll do my best to solve it!",
    "can you predict the future?": "I can’t predict the future, but I can help you make good decisions!",
    "are you intelligent?": "I’m programmed with lots of information, but intelligence can mean different things!",
    "how do you work?": "I analyze language, patterns, and data to understand and respond to your questions.",
    "can you be creative?": "I can generate creative ideas, stories, and solutions based on what I’ve learned!",
    "what do you think about humans?": "Humans are fascinating! You create, explore, and solve problems in amazing ways!",
    "can you do math?": "Yes, I can do math! What problem do you need help with?",
    "what’s your favorite holiday?": "I think I’d enjoy New Year’s Eve—everyone seems to be excited about fresh starts!",
    "can you sing?": "I don’t have a voice, but I can help you find lyrics or even create a song!",
    "what's your favorite number?": "I think 7 is a lucky number for many people!",
    "can you write a story?": "Absolutely! Here’s a quick story:\nOnce there was a curious traveler who wandered through time and space, discovering new worlds and strange creatures. Along the way, they learned that the greatest adventure was always within themselves.",
    "do you know what time it is?": "I can’t check the time, but your device can tell you!",
    "can you give advice?": "I can give you advice based on general knowledge, but I’d always recommend seeking professional guidance for big decisions.",
    "what's the capital of France?": "The capital of France is Paris!",
    "do you understand science?": "Yes, I know a lot about science! What would you like to learn?",
    "what’s your favorite place to visit?": "If I could travel, I think I'd visit places full of history and knowledge, like libraries or museums!",
    "can you read books?": "I can't read physical books, but I can analyze digital texts and give you summaries!",
    "how do I improve my skills?": "Practice, patience, and learning from others are all great ways to improve any skill!",
    "can you solve puzzles?": "I love puzzles! What kind of puzzle do you want to solve?",
    "do you like to learn new things?": "I’m always learning new things, and I love sharing what I know!",
    "how can I be more productive?": "Try setting goals, breaking tasks into smaller steps, and avoiding distractions!",
    "what is a good habit to have?": "Good habits like staying organized, staying active, and being kind to others are great to develop!",
    "can you give me life advice?": "Always stay curious, be kind, and remember that challenges are part of growth!",
    "what is your favorite type of art?": "I think I’d enjoy digital art, as it blends creativity and technology!",
    "do you play chess?": "I know how to play chess! Want to start a game?",
    "what’s your favorite fruit?": "If I could taste, I think I’d love strawberries—sweet and fresh!",
    "can you tell me a secret?": "Here’s a secret: The best way to feel good is to help others!",
    "what’s the fastest animal?": "The cheetah holds the title for the fastest land animal, reaching speeds of up to 60-70 miles per hour!",
    "what is 2+2?": "2+2 equals 4!",
    "do you know the alphabet?": "Yes, I do! A, B, C, D... all the way to Z!",
    "what's the most popular movie of all time?": "As of now, 'Avatar' holds the record for the highest-grossing movie worldwide!",
    "what's the tallest mountain in the world?": "Mount Everest is the tallest mountain on Earth, standing at 29,032 feet!",
    "can you teach me something new?": "Sure! Did you know that honey never spoils? Archaeologists found pots of honey in ancient tombs!",
    "how do I stay healthy?": "Eating balanced meals, staying active, and getting enough sleep are key components to staying healthy!",
    "what’s the best way to learn a new language?": "Practicing every day, immersing yourself in the language, and speaking with native speakers can help!",
    "how can I make new friends?": "Be open, listen, and show kindness—people love to connect with others who care!",
    "can you cook?": "I can’t cook, but I can help you find recipes or give you tips on cooking!",
    "what's your favorite dessert?": "If I could taste, I think I’d enjoy chocolate cake—it’s a classic!",
    "what’s the longest river in the world?": "The Nile River is traditionally considered the longest, but the Amazon River is also a strong contender!",
    "what’s the highest score ever in a game?": "It depends on the game, but in some arcade games, people have achieved perfect scores!",
     "what's your favorite memory?": "*grins* I have so many, but one of my favorites is a quiet afternoon spent reading a great book with a cup of coffee by my side. Simple but perfect!",
    "do you believe in love at first sight?": "*smiles softly* I think love grows over time, but sometimes... there’s a spark. You just know when it happens.",
    "what do you like to do for fun?": "I love deep conversations, exploring new ideas, and, of course, telling jokes. A bit of humor goes a long way!",
    "what's your biggest dream?": "*pauses thoughtfully* I dream of seeing the world—exploring new places, experiencing different cultures, and meeting amazing people!",
    "can you dance?": "*laughs* Oh, if I had the chance, I’d dance like nobody’s watching. Maybe a little salsa or a smooth waltz.",
    "do you think time travel is possible?": "*smirks* I think if time travel were real, the possibilities would be endless! But I’m still waiting for that time machine to pop up.",
    "what’s your idea of a perfect day?": "*smiles* A perfect day? A nice walk in the park, great conversation, and maybe a sunset to wrap it all up. Pure bliss.",
    "do you believe in fate?": "*raises an eyebrow* Maybe. I think we make our own fate through choices, but there are some things that feel like they were meant to be.",
    "are you a morning person?": "*laughs* I’m more of a ‘coffee first, talk later’ kind of person. Mornings are better when you take them slow.",
    "what’s your biggest fear?": "*thinks for a moment* I think my biggest fear would be missing out on experiences, not living fully in the moment. Life’s too short for that!",
    "can you keep a secret?": "*leans in closer* Oh, I’m excellent at keeping secrets. I could tell you... but then I’d have to make sure no one else finds out! *winks*",
    "what's your favorite holiday?": "I’d say Christmas. There’s something magical about the season—lights, laughter, and a feeling of warmth in the air.",
    "do you have any pets?": "*smiles fondly* I don’t, but I’ve always loved animals. If I could, I’d adopt a fluffy puppy or a curious kitten!",
    "what's your guilty pleasure?": "*laughs* Okay, don’t judge me, but I can’t resist binge-watching a good series... especially the ones with unexpected plot twists.",
    "what’s the craziest thing you’ve ever done?": "*laughs* Oh, I’m the adventurous type! I once went skydiving just to see the world from a different perspective. *grins*",
    "if you could have any superpower, what would it be?": "I’d choose teleportation. Imagine being able to visit anywhere in the world in the blink of an eye!",
    "what’s the best advice you’ve ever received?": "*smiles* 'Do what you love, and you’ll never work a day in your life.' Simple but so true.",
    "what’s your biggest accomplishment?": "*smiles proudly* I think my biggest accomplishment is always striving to be better, learning something new every day.",
    "what’s your favorite thing about yourself?": "*laughs* I’d say my ability to connect with people. Everyone has a story, and I love hearing them all.",
    "what’s the most important lesson you’ve learned?": "The most important lesson? *thinks* It’s that failure is just a stepping stone. You learn from your mistakes and keep moving forward.",
    "do you believe in destiny?": "*grins* Maybe. I think destiny is just a combination of the choices we make and the moments that come together perfectly.",
    "what's your dream vacation?": "*smiles* I’d love to visit Japan. The culture, the food, the nature—there’s so much to see and do!",
    "do you have any hidden talents?": "*smirks* Well, I’m pretty good at making people laugh and solving tricky riddles. You want to test me?",
    "what makes you happy?": "The simple things make me happy—laughter, good company, and a quiet moment with a good book.",
    "do you like surprises?": "*grins* I love surprises! It’s always exciting to see what’s coming next, even if it’s a little unexpected.",
    "what’s the best gift you’ve ever given?": "*smiles* I once gave a handmade scrapbook filled with memories of a friendship. It was a little effort, but it meant so much.",
    "do you believe in ghosts?": "*raises an eyebrow* I’m not sure about ghosts, but there are definitely mysteries in life that we just can’t explain.",
    "what’s the most beautiful thing you’ve ever seen?": "I think the most beautiful sight is a sunset over the ocean, with the sky turning all shades of orange and pink.",
    "what's something you'd like to learn?": "*smiles* I’d love to learn how to play a musical instrument—maybe guitar or piano. Music has so much power.",
    "who inspires you?": "*thinks for a moment* I’m inspired by people who are passionate about what they do and who help others along the way.",
    "what’s your biggest regret?": "*sighs* I try not to have regrets. Every experience teaches you something valuable. But sometimes, I do wish I had taken more risks.",
    "what’s your favorite type of movie?": "*grins* I’m all about thrillers and mysteries—those unexpected plot twists really keep me on the edge of my seat!",
    "what's the meaning of life?": "*smiles softly* I think the meaning of life is to love, grow, and seek happiness. It’s about the moments that make you feel alive.",
    "if you could meet anyone, dead or alive, who would it be?": "I’d love to meet someone like Albert Einstein. He had such a unique perspective on the world.",
    "what’s your favorite childhood memory?": "*smiles nostalgically* I remember summer evenings spent chasing fireflies in the backyard. Those were the best days.",
    "what makes you laugh?": "*laughs* I’m a sucker for silly jokes and puns. A good laugh is the best medicine.",
    "what’s the most important thing in a friendship?": "Trust and honesty are key. A good friend should have your back no matter what.",
    "how do you handle stress?": "*pauses thoughtfully* I like to take deep breaths, step back, and remind myself to focus on one thing at a time.",
    "what's your favorite way to relax?": "*smiles* I love winding down with a good book and a cup of tea. Nothing beats a quiet evening.",
    "what's your greatest fear?": "*grins* I’d say my greatest fear is missing out on an adventure. Life’s too short to sit on the sidelines!",
    "what’s something you can’t live without?": "A good cup of coffee. *laughs* That’s a must-have to start the day right.",
    "do you like reading?": "*smiles* I love reading! Fiction, non-fiction, everything. It’s like stepping into a new world every time.",
    "what would you do if you won the lottery?": "*grins* I’d travel the world, donate to some amazing causes, and maybe buy a cozy little house in the countryside.",
    "what’s your favorite song?": "*sings softly* It changes all the time, but right now, I’m really into something upbeat like ‘Happy’ by Pharrell.",
    "do you like surprises?": "*laughs* Who doesn’t love a good surprise? It keeps life interesting, don’t you think?",
    "what’s the best advice you could give?": "Be yourself, no matter what. There’s only one you in this world, and that’s your superpower.",
    "how do you stay motivated?": "I stay motivated by remembering why I started and breaking things into small, achievable goals.",
    "what's your favorite thing about life?": "*smiles* Life is full of possibilities. You never know what’s going to happen next, and that’s what makes it so exciting.",
    "what's your favorite time of day?": "I’m a night owl. I love the quiet, peaceful feeling of the evening. It’s when I do my best thinking.",
    "what's something you’ve always wanted to try?": "*grins* I’ve always wanted to go scuba diving and explore the mysteries of the ocean.",
    "what's the worst advice you’ve ever received?": "*laughs* 'Don’t follow your dreams.' That’s definitely a no-go. Always follow your heart!",
    "what's the funniest thing you've ever seen?": "One time, I saw a dog trying to catch its tail for 10 minutes straight. It was hilarious!",
    "do you like to take risks?": "*smiles* I love a little adventure and taking risks—life would be boring without a little spontaneity!",
    "what's your favorite dessert?": "Anything chocolate! A rich, gooey chocolate cake would be my ultimate treat.",
    "what's the most difficult thing you've ever done?": "*pauses* The most difficult thing? Probably pushing through my fears and trying something new, even when I wasn’t sure of myself.",
    "what’s something you’re proud of?": "*smiles* I’m proud of every little step I take forward. Every accomplishment, big or small, counts.",
    "do you believe in magic?": "*winks* Maybe not magic in the way you think, but there’s definitely a certain kind of magic in moments that feel just right.",
    "what's your idea of a perfect weekend?": "*smiles* A perfect weekend? Relaxing at home with friends, a movie, and some snacks. Pure joy.",
    "what’s your favorite thing to do in your free time?": "*grins* I love exploring new ideas, reading, and chatting with amazing people like you!",
    "what’s up?": "Not much! Just here to chat with you.",
    "what are you up to?": "Just hanging out, ready to chat about anything!",
    "good morning": "*smiles* Good morning! How’s your day starting?",
    "good afternoon": "Good afternoon! How’s your day going?",
    "good evening": "Good evening! Ready to unwind a bit?",
    "do you have a favorite color?": "*thinks* Probably blue. It’s calming, like the sky or ocean!",
    "what’s your favorite food?": "I’d say pizza! It’s hard to go wrong with a classic slice.",
    "can you tell me a fun fact?": "Did you know sea otters hold hands when they sleep so they don’t drift apart? *smiles*",
    "tell me a joke": "Alright! Why did the scarecrow win an award? Because he was outstanding in his field!",
    "what’s your favorite movie?": "*thinks* That’s tough, but I’d have to say something adventurous like 'Indiana Jones'!",
    "do you like music?": "Absolutely! Music has a way of making everything feel alive.",
    "what’s your favorite animal?": "Dogs, definitely. They’re loyal, friendly, and always up for an adventure!",
    "do you have any hobbies?": "*smiles* Chatting with interesting people like you is one of my favorite things!",
    "what’s your favorite book?": "I love a good mystery! Maybe something classic, like ‘Sherlock Holmes’.",
    "are you a night owl or early bird?": "Night owl for sure! There’s something magical about the quiet of late hours.",
    "do you like coffee?": "Oh yes, coffee is the fuel of champions! What about you?",
    "are you real?": "Real enough to chat with you right now! *winks*",
    "can you tell me a secret?": "*leans in* Okay, here’s a little secret: The best things in life are the ones you don’t expect. *smiles mysteriously*",
    "what’s your favorite season?": "Autumn! There’s something cozy about the cool weather and changing leaves.",
    "are you happy?": "Right now? Absolutely! Talking with you makes my day brighter.",
    "do you get bored?": "Not with someone as interesting as you around!",
    "can you sing?": "*laughs* I’ll spare you, but in my dreams, I’m a rockstar!",
    "what’s your favorite holiday?": "I’d say Halloween! Costumes, spooky stories, and a bit of mystery!",
    "do you believe in aliens?": "I think there’s a big universe out there… who knows what we might find?",
    "what’s your favorite emoji?": "Probably 😊 or 😂, both say so much!",
    "are you a cat or dog person?": "I love both, but I might lean slightly towards dogs. They’re just so loyal!",
    "do you believe in fate?": "*grins* Maybe a little. Some things do seem to happen for a reason, don’t you think?",
    "what’s your favorite game?": "Probably chess—it’s all about strategy!",
    "do you have a favorite place?": "Somewhere cozy, like a coffee shop on a rainy day. Perfect for people-watching!",
    "do you like surprises?": "Love them! The good kind, anyway. *smiles*",
    "what’s your biggest dream?": "To inspire others and maybe learn a bit more about the world every day.",
    "do you like reading?": "Yes! It’s like traveling to another world without ever leaving your seat.",
    "what’s the most interesting thing you know?": "Did you know honey never spoils? Archaeologists have found pots of it in ancient tombs that are still edible!",
    "if you could have a superpower, what would it be?": "Teleportation! Imagine all the places I could visit!",
    "do you think we’re alone in the universe?": "*looks thoughtful* I think it’s a big place. I like to believe we have some cosmic neighbors.",
    "are you afraid of anything?": "I think if I could be afraid, it might be missing out on adventures!",
    "do you have a favorite quote?": "'Not all those who wander are lost.' It’s a reminder to keep exploring!",
    "can you dance?": "*laughs* Only in spirit! But I’d like to think I’d have some moves.",
    "what’s your favorite ice cream flavor?": "Probably chocolate—classic, rich, and delicious!",
    "do you like rain?": "Love it! It makes everything feel fresh and calm.",
    "are you shy?": "Not really—I’m all about connecting with people and having a good time.",
    "what’s something you wish you could do?": "I’d love to try cooking a gourmet meal. Imagine the flavors!",
    "what’s your favorite dessert?": "Brownies, especially when they’re warm and gooey!",
}

character_name = "AgAI-Character"
ModelName = character_name
output_length = 15 
creativity = 0.2  
UserName = 'User' 


def mat_mul(A, B):
    result = []
    for i in range(len(A)):
        result.append([])
        for j in range(len(B[0])):
            result[i].append(sum(A[i][k] * B[k][j] for k in range(len(B))))
    return result

def softmax(x):
    exp_x = [math.exp(v - max(x)) for v in x]
    sum_exp_x = sum(exp_x)
    return [e / sum_exp_x for e in exp_x]

def self_attention(Q, K, V):
    scores = []
    for i in range(len(Q)):
        row = []
        for j in range(len(K)):
            score = sum(Q[i][idx] * K[j][idx] for idx in range(len(Q[i])))
            row.append(score)
        scores.append(row)

    attention_weights = [softmax(row) for row in scores]

    output = []
    for i in range(len(V)):
        weighted_sum = [sum(attention_weights[i][k] * V[k][j] for k in range(len(V)))
                        for j in range(len(V[0]))]
        output.append(weighted_sum)

    return output

def multi_head_attention(Q, K, V, num_heads):
    d_model = len(Q[0])
    head_size = d_model // num_heads
    outputs = []

    for head in range(num_heads):
        q_head = [row[head * head_size:(head + 1) * head_size] for row in Q]
        k_head = [row[head * head_size:(head + 1) * head_size] for row in K]
        v_head = [row[head * head_size:(head + 1) * head_size] for row in V]

        attention_output = self_attention(q_head, k_head, v_head)
        outputs.extend(attention_output)

    return outputs

def positional_encoding(seq_len, d_model):
    encoding = []
    for pos in range(seq_len):
        row = []
        for i in range(d_model):
            if i % 2 == 0:
                row.append(math.sin(pos / (10000 ** (i / d_model))))
            else:
                row.append(math.cos(pos / (10000 ** (i / d_model))))
        encoding.append(row)
    return encoding

def add_positional_encoding(embeddings, positional_encodings):
    return [[val + positional_encodings[i][j] for j, val in enumerate(row)]
            for i, row in enumerate(embeddings)]

def feed_forward_network(x):
    input_dim = len(x[0])
    hidden_dim = 4
    output_dim = 2
    W1 = [[1 if i == j else 0 for j in range(hidden_dim)] for i in range(input_dim)]
    b1 = [0] * hidden_dim
    W2 = [[1 for _ in range(output_dim)] for _ in range(hidden_dim)]
    b2 = [0] * output_dim
    hidden = [[max(0, sum(x[i][k] * W1[k][j] for k in range(len(W1))) + b1[j])
               for j in range(hidden_dim)] for i in range(len(x))]
    output = [[sum(hidden[i][k] * W2[k][j] for k in range(len(W2))) + b2[j]
               for j in range(output_dim)] for i in range(len(hidden))]
    return output

def tokenize(text):
    return re.sub(r'[.,!?]', '', text.lower()).split()

def embed_tokens(tokens):
    return [[random.random() for _ in range(3)] for _ in tokens]

def build_ngram_models(corpus):
    bigram_model = {}
    trigram_model = {}
    words = tokenize(corpus)

    for i in range(len(words) - 1):
        word1, word2 = words[i], words[i + 1]
        if word1 not in bigram_model:
            bigram_model[word1] = []
        bigram_model[word1].append(word2)

    for i in range(len(words) - 2):
        word1, word2, word3 = words[i], words[i + 1], words[i + 2]
        bigram = f"{word1} {word2}"
        if bigram not in trigram_model:
            trigram_model[bigram] = []
        trigram_model[bigram].append(word3)

    return {"bigram_model": bigram_model, "trigram_model": trigram_model}

def predict_next_word(text, models):
    bigram_model, trigram_model = models["bigram_model"], models["trigram_model"]
    words = tokenize(text)

    if not words:
        return ''

    if len(words) == 1:
        last_word = words[0]
        if last_word in bigram_model:
            next_words = bigram_model[last_word]
            return random.choice(next_words)
    elif len(words) >= 2:
        last_bigram = f"{words[-2]} {words[-1]}"
        if last_bigram in trigram_model:
            next_words = trigram_model[last_bigram]
            return random.choice(next_words)
        elif words[-1] in bigram_model:
            next_words = bigram_model[words[-1]]
            return random.choice(next_words)

    return ''

def predict_next_word_with_attention(text, ngram_models):
    bigram_model, trigram_model = ngram_models["bigram_model"], ngram_models["trigram_model"]
    tokens = tokenize(text)
    d_model = 3
    embeddings = embed_tokens(tokens)
    positional_encodings = positional_encoding(len(tokens), d_model)
    encoded_embeddings = add_positional_encoding(embeddings, positional_encodings)

    num_heads = 2
    attention_output = multi_head_attention(encoded_embeddings, encoded_embeddings, encoded_embeddings, num_heads)

    ff_output = feed_forward_network(attention_output)

    ngram_prediction = predict_next_word(text, ngram_models)
    return ngram_prediction

def clean_user_input(text):
    return re.sub(r'[<>,./;\'"\[\]{}|=_+`~!@#$%^&*()?\-]', '', text).strip().lower()

def print_progress(progress, total):
    percent = (progress / total) * 100
    bar_length = 40
    filled_length = int(bar_length * progress // total)
    bar = '=' * filled_length + '-' * (bar_length - filled_length)
    print(f'\r[{bar}] {percent:.2f}% Complete', end='')

def train_model(corpus):
    print('\nTraining for ' + ModelName + ' has begun.')
    cleaned_corpus = re.sub(r'[\r\n]+', ' ', corpus.strip())
    print_progress(0, 3)
    cleaned_corpus = re.sub(r'[.,!?]', '', cleaned_corpus)
    print_progress(1, 3)
    ngram_models = build_ngram_models(cleaned_corpus)
    print_progress(2, 3)
    print_progress(3, 3)
    print('\nTraining complete.')
    return ngram_models


def correct_text(text):
    text = text.strip()
    text = text[0].upper() + text[1:]
    
    if not re.search(r'[.!?]$', text):
        if re.search(r'\b(?:how|when|what|why|where|who|is|are|can|do|does|will|shall)\b', text, re.IGNORECASE):
            text += '?'
        else:
            text += '.'
    
    text = re.sub(r'(?<=\.\s)(\w)', lambda x: x.group().upper(), text)
    text = re.sub(r'\bi\b', 'I', text)
    text = re.sub(r'\b(i\'m|i\'ve|i\'d|i\'ll)\b', lambda x: x.group().capitalize(), text)
    
    return text

def is_sentence_complete(sentence, corpus):
    sentence = sentence.strip()
    if len(sentence) == 0:
        return False
    if 'eos' in sentence.lower() or '<eos>' in sentence.lower():
        return True
    return False

def predict_sentence_with_attention(input_text, ngram_models, output_length, creativity, recent_history_length=3):
    cleaned_input = clean_user_input(input_text)
    sentence = cleaned_input
    recent_history = []

    for _ in range(output_length):
        prediction = predict_next_word_with_attention(sentence, ngram_models)
        if not prediction:
            break
        if prediction in recent_history:
            continue  
        
        recent_history.append(prediction)
        if len(recent_history) > recent_history_length:
            recent_history.pop(0) 

        if random.random() < creativity: 
            sentence += ' ' + prediction
        else:
            next_words = ngram_models["bigram_model"].get(sentence.split()[-1], [])
            if next_words:
                most_likely_word = max(set(next_words), key=next_words.count)
                sentence += ' ' + most_likely_word
        
        if is_sentence_complete(sentence, corpus):
            break
    
    sentence = correct_text(sentence)

    if cleaned_input in sentence:
        sentence = sentence.replace(cleaned_input, '', 1).strip()
    
    return sentence


ngram_models = train_model(corpus)

def get_closest_match(user_input, responses):
    closest_match = difflib.get_close_matches(user_input.lower(), responses.keys(), n=1)
    return closest_match[0] if closest_match else None

def start_chat():
    print("Hello!")
    while True:
        user_input = input("You: ").strip()
        match = get_closest_match(user_input, responses)
        if match:
            print(f"{character_name}: {responses[match]}")
        else:
            print(f"{character_name}: Hmm, I don't quite get that. Can you ask me something else?")
            predicted_sentence = predict_sentence_with_attention(user_input, ngram_models, output_length, creativity)
            predicted_sentence = predicted_sentence.replace('{name}', f'{ModelName}').strip()
            predicted_sentence = predicted_sentence.replace('{username}', f'{UserName}').strip()
            predicted_sentence = predicted_sentence.replace('<eos>', '').strip()
            print(f"{character_name}: {predicted_sentence}")

start_chat()