Hello, chatbot: the 30-line MVP
This is the lesson where you become someone who has built an AI app. After today, you can never go back to "I am learning AI". You are doing AI.
Hanging your first painting on your own wall. The bar is just "exists and works". Polish comes later.
The MVP has:
- A title and intro line
- A chat input box
- A chat history display
- A function that calls OpenAI and appends the reply
- Session state to remember history
That is it.
import streamlit as st
from openai import OpenAI
from dotenv import load_dotenv
load_dotenv()
client = OpenAI()
st.title("GeekBot: my first AI chat")
if "messages" not in st.session_state:
st.session_state.messages = []
for msg in st.session_state.messages:
with st.chat_message(msg["role"]):
st.markdown(msg["content"])
if prompt := st.chat_input("Ask me anything"):
st.session_state.messages.append({"role": "user", "content": prompt})
with st.chat_message("user"):
st.markdown(prompt)
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=st.session_state.messages,
)
reply = response.choices[0].message.content
st.session_state.messages.append({"role": "assistant", "content": reply})
with st.chat_message("assistant"):
st.markdown(reply)
That is a working chatbot. About 30 lines.
Quick recall
3 prompts · think before you flip
Prompt 1 of 3
What does `st.session_state` do?
Quiz time
1 question · tap an answer to check it
1. The chatbot remembers context because
Finished lesson 6.2?
Mark complete to update your module progress and unlock the streak.
Loading