Generative AIby Dhruv Narang

What Is a Chatbot?

You already use chatbots, like ChatGPT. You type a message, you get an answer, and you can keep going. In this lesson you build a small one that runs in the terminal.

Definition

A chatbot is a loop. It asks you for a message, sends it to the model, shows the answer, and asks again.

What you will see when you run it
welcome to chatbot type exit to quit
You : ask any think: What is the capital of India?
Bot: The capital of India is New Delhi.
You : ask any think: What is 5 plus 3?
Bot: 5 plus 3 is 8.
You : ask any think: exit
An example run. Your answers will be a little different.
1. You type
A message
The program waits for you.
2. The model
Gets your message
It writes an answer.
3. The answer
Is shown
The program prints it.
4. Again
Back to step 1
Until you type exit.
A chatbot is a loop. The same four steps repeat. In code, that loop is a while loop.

The Code

The whole chatbot is a few lines. Run it, type a question, and type exit to stop.

from dotenv import load_dotenv
load_dotenv()

from langchain.chat_models import init_chat_model

model = init_chat_model("mistralai:mistral-small-2603", temperature=0.7)

print("welcome to chatbot type exit to quit")

while True:
    user_input = input("You : ask any think: ")
    if user_input == "exit":
        break

    response = model.invoke(user_input)

    print(f"Bot: {response.content}")
The model is created once, before the loop. The loop only asks and answers.
This chatbot has no memory yet. Every question goes to the model on its own. The next lesson fixes that.