Lecture 103 · Practical AIExercise 103.1
ECE study buddy
Build a small study helper in the terminal. It answers ECE questions and remembers the chat. You use only what you saw in class: one API call, the messages list, roles, the JSON reply and the system prompt.
- 45 min
- Beginner
- You build A terminal chat helper that answers ECE questions and remembers the chat
Before you start: Python must work on your laptop. If not, do the Python setup first (one time).
Part A
Get the code and a key
Do Part A one time. After it, the lecture code and your key are ready.
Download the code
Download lec103-code.zip 23 KB
Right-click the zip file. Click Extract All. Put the folder
lec103-codeinside yourai-ecefolder.Double-click the zip file. Move the folder
lec103-codeinto yourai-ecefolder.Unzip it in your
ai-ecefolder:unzip lec103-code.zip.Sometimes you get a folder inside a folder with the same name. Use the folder that has
README.mdin it. The folderexercise-103.1is already in it.Go into the folder
In VS Code, open the
ai-ecefolder and a new terminal. Turn the venv on. Then go into the code folder:cd lec103-codeThe prompt must start with
(.venv). If not, see setup step 6.Make a free OpenRouter account
OpenRouter gives free AI models. You do not need a card. Go to openrouter.ai and sign up.
Make a key
Open Keys. Click Create key. Give it a name, for example
ece-lab. Copy the key. OpenRouter shows it only one time.Your key is you. Keep it secret. Do not share it in WhatsApp or email. Do not put it in a
.pyfile. Do not upload.envto GitHub. If someone sees your key, delete it on the Keys page and make a new one.Put the key in .env
In the
lec103-codefolder, copy the example file to a new file with the name.env:Copy-Item .env.example .envcp .env.example .envOpen
.envin VS Code. Paste your key afterAPI_KEY=. Do not add spaces or quotes. Save the file (Ctrl + S, or Cmd + S on macOS).API_KEY=paste-your-key-here URL=https://openrouter.ai/api/v1/chat/completions MODEL=google/gemma-4-31b-it:freeDo not change
URL.MODELis a free model: its name ends in:free.Check: run your first AI call
cd 0-basics python 01_first_call.py cd ..Type a question and press Enter. The answer from the model comes back in a few seconds. You see an answer? Part A is done. You see an error? Read If something goes wrong.
Part B
Build the study buddy
Go to the exercise folder and run the starter file. You see the full JSON reply.
cd exercise-103.1
python starter.pystarter.py
You already have this file. It is in lec103-code/exercise-103.1/ from the zip in Part A. It works as it is. Each TODO is one step below. Change this file.
# Exercise 103.1 - ECE study buddy (starter file)
# This file works as it is. Run it first: python starter.py
# Then do steps 1 to 6 from README.md. Each step has a TODO below.
import requests
from config import API_KEY, URL, MODEL
# TODO 1: Change this question to an ECE question.
question = "What is AI?"
# TODO 3: Make a "messages" list. Put a system message first, then the user message.
# TODO 4: Put the code from here to the end in a "while True:" loop.
# Read the question with input(). Stop the loop when the user types "quit".
# TODO 5: Make the "messages" list one time, before the loop.
# Add each question and each answer to it.
response = requests.post(
URL,
headers={"Authorization": "Bearer " + API_KEY},
json={"model": MODEL, "messages": [{"role": "user", "content": question}]},
)
data = response.json()
# TODO 1: This prints the full JSON reply. Print only the answer text.
print(data)
# TODO 2: Print the tokens used. Use data.get("usage", {}).
# TODO 6 (bonus): Add up the tokens of all the turns. Print the total after each answer.
Do the steps in order. Run the file after each step.
Ask an ECE question
- Goal
- Ask an ECE question. Print only the answer text.
- Hint
- Change the
questionline. The answer text is atdata["choices"][0]["message"]["content"]. - Check
- You see only the answer. You do not see
{'id': ...
Print the tokens
- Goal
- Print the number of tokens for this call.
- Hint
- Write
usage = data.get("usage", {}). Then printusage.get("prompt_tokens"),usage.get("completion_tokens")andusage.get("total_tokens"). - Check
- You see three numbers. Input + output = total.
Add a system prompt
- Goal
- Give the model a job.
- Hint
- Make a
messageslist. Put this message first:
Put the user message second. Send{"role": "system", "content": "You are a friendly tutor for ECE students. Answer in 3 short lines."}messagesin thejson=part. - Check
- The answer has 3 short lines. Put
#before the system message and run again. Compare the two answers.
Ask many questions
- Goal
- Ask questions again and again. Type
quitto stop. - Hint
- Put the code in a
while True:loop. Usequestion = input("You: "). Usebreakwhen the text isquit. - Check
- Type
my name is Ravi. Then typewhat is my name?. The model does not know. It has no memory.
Give it a memory
- Goal
- The model remembers the chat.
- Hint
- Make the
messageslist one time, before the loop. In the loop, append the user message. After the answer, append{"role": "assistant", "content": answer}. Send the whole list each time. - Check
- Type
my name is Ravi. Then typewhat is my name?. The model says “Ravi”.
Bonus: watch the tokens grow
- Goal
- Print the total tokens after each turn.
- Hint
- Before the loop, write
tokens_so_far = 0. After each answer, addusage.get("total_tokens", 0)to it. Print it. - Check
- The input tokens grow each turn. Why? You send the whole history each time. A long chat costs more.
Solution
Try each step first. Then compare your code with the solution.
Test it: type my name is Ravi, then what is my name?, then quit.
If something goes wrong
KeyError: ‘choices’
The API sent back an error, not an answer. Print data to see it. In 0-basics/01_first_call.py, remove the # before print(data). Run it again. Find the error code (401, 404 or 429) below.
Error 401 (no auth credentials / user not found)
The key is wrong or missing. Open .env. Make sure your key comes right after API_KEY=, with no spaces and no quotes. Save the file. Make sure the file name is exactly .env and it is in the lec103-code folder.
If Notepad saved it as .env.txt, rename it to .env in VS Code.
Error 429 (rate limit / too many requests)
Free models have limits: a few requests per minute and a daily limit. Many people use the same free model, so it is sometimes busy. Wait one minute and try again. Or change MODEL in .env to a fallback:
MODEL=google/gemma-4-26b-a4b-it:free
MODEL=openrouter/freeKeep only one MODEL= line in .env.
Error 404 (model not found / no endpoints found)
Check the MODEL line for typos. Free models change over time. Find a current one at openrouter.ai/models (filter: free).
If the message says “matching your data policy”: open openrouter.ai/settings/privacy and allow the free models.
ModuleNotFoundError: No module named ‘config’
You are in the wrong folder. First cd into the folder of the program, for example cd exercise-103.1 or cd 0-basics, then run it.
Python errors (python not found, pip, venv, No module named ‘requests’): common errors in the Python setup.
Already have lec103-code from class, but no exercise-103.1 folder? Download only exercise-103.1.zip and put the folder inside lec103-code.