Codiqo

Understanding AI · lesson 41 of 60 · about 6 minutes

Guess the Next Word

Every chatbot is built on one trick: guessing the next word. Build a tiny next-word guesser from word pairs.

What you'll learn

  • Explain that chatbots predict the next word
  • Build a table of which words follow which
  • Use the table to guess the next word

The one trick

Your phone keyboard suggests the next word as you type. Chatbots do exactly the same thing, just far, far better: given all the words so far, they predict the next one.

That's it. Everything a chatbot writes comes from guessing the next word, again and again.

A tiny text, and a table of which words follow each word. It's a dictionary of dictionaries: for each word, the counts of what came next.

words = "i like cats . i like dogs . i like cats . you like cats .".split()
following = {}
for a, b in zip(words, words[1:]):
    if a not in following:
        following[a] = {}
    following[a][b] = following[a].get(b, 0) + 1
print(following["like"])
print(following["i"])

Output

{'cats': 3, 'dogs': 1}
{'like': 3}

Tip

After like, this text had cats 3 times and dogs once. So the best guess after like is cats.

Now try it yourself

This lesson is free in Codiqo, with 6 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.