AI for ECE

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.

Before you start: Python must work on your laptop. If not, do the Python setup first (one time).

Your computer:

Part A

Get the code and a key

Do Part A one time. After it, the lecture code and your key are ready.

  1. Download the code

    Download lec103-code.zip 23 KB

    Right-click the zip file. Click Extract All. Put the folder lec103-code inside your ai-ece folder.

    Double-click the zip file. Move the folder lec103-code into your ai-ece folder.

    Unzip it in your ai-ece folder: unzip lec103-code.zip.

    Sometimes you get a folder inside a folder with the same name. Use the folder that has README.md in it. The folder exercise-103.1 is already in it.

  2. Go into the folder

    In VS Code, open the ai-ece folder and a new terminal. Turn the venv on. Then go into the code folder:

    cd lec103-code

    The prompt must start with (.venv). If not, see setup step 6.

  3. Make a free OpenRouter account

    OpenRouter gives free AI models. You do not need a card. Go to openrouter.ai and sign up.

  4. 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 .py file. Do not upload .env to GitHub. If someone sees your key, delete it on the Keys page and make a new one.

  5. Put the key in .env

    In the lec103-code folder, copy the example file to a new file with the name .env:

    Copy-Item .env.example .env
    cp .env.example .env

    Open .env in VS Code. Paste your key after API_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:free

    Do not change URL. MODEL is a free model: its name ends in :free.

  6. 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.py

starter.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.

  1. Ask an ECE question

    Goal
    Ask an ECE question. Print only the answer text.
    Hint
    Change the question line. The answer text is at data["choices"][0]["message"]["content"].
    Check
    You see only the answer. You do not see {'id': ...
  2. Print the tokens

    Goal
    Print the number of tokens for this call.
    Hint
    Write usage = data.get("usage", {}). Then print usage.get("prompt_tokens"), usage.get("completion_tokens") and usage.get("total_tokens").
    Check
    You see three numbers. Input + output = total.
  3. Add a system prompt

    Goal
    Give the model a job.
    Hint
    Make a messages list. Put this message first:
    {"role": "system", "content": "You are a friendly tutor for ECE students. Answer in 3 short lines."}
    Put the user message second. Send messages in the json= part.
    Check
    The answer has 3 short lines. Put # before the system message and run again. Compare the two answers.
  4. Ask many questions

    Goal
    Ask questions again and again. Type quit to stop.
    Hint
    Put the code in a while True: loop. Use question = input("You: "). Use break when the text is quit.
    Check
    Type my name is Ravi. Then type what is my name?. The model does not know. It has no memory.
  5. Give it a memory

    Goal
    The model remembers the chat.
    Hint
    Make the messages list 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 type what is my name?. The model says “Ravi”.
  6. 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, add usage.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.

The solution is locked. Type the key to see it. If you need the key, ask your teacher.

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/free

Keep 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.