Sharda University

Artificial Intelligence 103

Practical AI · Specialized for ECE

Recap · Why · Practical AI · Add AI to an app · Lab
Today

Short theory. Then you build.

01 · RECAP
Fast refresher
The words from 101 and 102, one slide each.
02 · WHY
AI is not optional
Where it is used, and what jobs now ask for.
03 · PRACTICAL AI
Agents, tools, API calls
Agents, tools, and the five parts you need to add AI to an app.
04 · LAB
Six steps, three apps
From one API call to a small agent, then your own apps.
Recap · What AI is

Machines imitating things humans do

Language, recognition, judgment — performed without anyone writing an explicit rule for each case.

Recap · AI ⊃ ML ⊃ DL

AI contains ML. ML contains deep learning.

ARTIFICIAL INTELLIGENCE
MACHINE LEARNING
The machine fits its own rules from examples.
Example: a spam filter trained on a million labelled emails.
DEEP LEARNING
LLMs live here
One way to build AI. Today, the most common one.
ALSO AI, WITH NO LEARNING AT ALL
Rule-based systems
An engineer writes if / then rules: “if cell temperature > 45 °C, stop charging.”
Search
Route finding in a maps app: try the possible paths, keep the shortest one.
Expert systems
MYCIN (1970s): about 600 rules from doctors, used to suggest antibiotics.
Hand-written game players
Deep Blue beat Kasparov in 1997 with fast search and hand-built scoring rules.
AI contains machine learning. But you can have AI without machine learning.
Recap · Who writes the rules

The difference is who writes the rules

SOFTWARE YOU HAVE WRITTEN
A human writes every rule
You decide each case in advance, by hand — if subject contains "lottery". You maintain that list forever, and it fails on the case you did not foresee.
MACHINE LEARNING
Nobody writes the rules
Show it a million labelled emails and the rule is fitted from the examples. It fails on the case that looks unlike anything it was shown.
Now try to hand-write the rules for “is there a cat in this photo?” The moment you cannot, you have found the reason this field exists.
Recap · What AI is not

Good imitation. Not a brain. Not AGI.

TURING TEST · 1950
Can a judge tell?
A judge chats by text with a hidden human and a hidden machine. Today's chatbots often fool people in short chats.
NOT A BRAIN
Pattern-fitting at scale
It imitates human-like answers. Impressive imitation is still imitation.
NOT AGI
Not built yet
AGI = matches people at nearly every mental task. Even the best models today are narrow AI.
Fooling a judge in a short chat shows good imitation. It does not show understanding.
Recap · Why now · 1

The maths was always there

2012 → The boom same ideas, finally at scale 19501960197019801990200020102020 1958 Perceptron Rosenblatt: one neuron that learns 1986 Backpropagation Rumelhart, Hinton & Williams 1997 LSTM Hochreiter & Schmidhuber 1989–98 CNNs · LeNet LeCun: reads handwritten digits
These methods existed for decades. Backpropagation, the method that trains today’s models, is from 1986.
Recap · Why now · 2

What changed is scale

INPUT 1
Data
THEN · 199860,000 digit images
NOW · 2024~15 trillion words
The internet became a training set. Bars not to scale: the real gap is far bigger.
INPUT 2
Compute
THEN · CPUa few cores
NOW · GPUthousands of MACs
A GPU is a parallel MAC farm. Training runs use thousands of GPUs at once.
INPUT 3
One architecture
THEN · LENET~60 thousand weights
NOW · TRANSFORMERhundreds of billions
The transformer (2017) keeps improving as you make it bigger, for text, images, audio and code.
Same maths+ scale= today’s AI
Recap · Everything is numbers

Computers only work with numbers

A computer can only do arithmetic. So text, images and sound must first become numbers.
TEXT
Hi!
→
7210533
Each character has an ID number: H = 72, i = 105, ! = 33.
IMAGE
→
210 65 47232 154 44244 211 9458 111 176…
A grid of pixels. Each pixel = red, green, blue, each from 0 to 255.
SOUND
→
0.540.75−0.46−0.750.460.75…
The ADC samples the mic voltage: 44,100 numbers every second.
SENSOR
LM35
→
0.31
A temperature sensor gives a voltage: 0.31 V means 31 °C.
So a model takes numbers in, does maths, and gives numbers out.
Recap · What a model is

A model is a file of learned numbers

A large file of numbers — the weights. The computer uses these numbers to make the prediction.
Nobody typed in its behaviour. It was trained: the numbers were changed again and again on data until the output was right.
Next: what these numbers are and what they do.
ON DISK
llama-3.2-3b.gguf
2.3 GB
llamamodel family (made by Meta) 3.2version 3b3 billion learned numbers .gguffile type, like .mp3 or .pdf
That is the whole model. One file. You can copy it like any other file.
Recap · Weights and parameters

A weight is one learned number

y = w·x + b
INPUT x = 2 × w w = 0.5 + b b = 1 OUTPUT y = 2 w and b were not typed in by a person. Training found them.
Weight w
The multiplier. How strongly an input counts.
Bias b
The offset. Shifts the result up or down.
Parameters
All the learned numbers: weights + biases. In normal talk, “parameters” ≈ “weights”.
Recap · Parameter counts

What “7B” and “70B” actually mean

M = million, B = billion. 7B = seven billion learned numbers in the file.
110MBERT-base (Google, 2018)
1.5BGPT-2 (OpenAI, 2019)
8BLlama 3.1 8B — runs on a laptop
70BLlama 3.1 70B — needs a workstation
405BLlama 3.1 405B — needs a server
1T+Largest open models (Kimi, DeepSeek, Qwen)
More parameters
Usually more capable: better at long instructions and rare facts.
…but slower and costlier
More numbers to store and multiply for every word.
Closed models (GPT, Claude, Gemini): sizes not published. Outside guesses: a few hundred billion to a few trillion.
Recap · Scale · published sizes and outside guesses, Oct 2026

How big are the big ones?

PUBLISHED BY THE MAKER · open-weight models
Llama 3.1 405B · Meta
405B
Kimi K2 · Moonshot
1T · 32B
DeepSeek V4-Pro
1.6T · 49B
Qwen3.8 flagship · Alibaba
2.4T · 95B
Kimi K3 · Moonshot
2.8T · 104B
GUESSED BY OUTSIDERS · closed models · companies do not publish sizes
Claude 3.5 Sonnet · Anthropic
Microsoft research paper, Dec 2024
≈175B est.
GPT-4o · OpenAI
Microsoft research paper, Dec 2024
≈200B est.
GPT-4 · OpenAI
leaks, 2023 (SemiAnalysis, G. Hotz)
≈1.8T est.
Gemini 3 Pro · Google
one analyst, Nov 2025 (LifeArchitect)
≈3T est.
total active per word estimate — not confirmed by the company No public guess yet for GPT-6, Claude 5.5 or Gemini 4.
Recap · Families & tiers · Oct 2026

One family, several size points

CLAUDE TIER
CHARACTER
USE IT WHEN
Haiku
Smallest, fastest, cheapest
Many simple jobs, quick answers
Sonnet
Balanced everyday model
Most daily tasks and most of this course
Opus
Large, strong reasoning
Hard problems where a wrong answer costs a lot
Fable
Top tier, above Opus, most costly
Long, difficult jobs that run for hours
Same idea elsewhere: OpenAI has GPT-6 Luna, Sol and Astra; Google has Gemini Flash and Gemini 4 Argon. Picking a tier is a cost-versus-capability trade, like choosing a component grade.
Recap · Memory

How much memory a model needs

memory ≈ parameters × bytes per parameter
FP16 = 2 B · 4-bit ≈ 0.5 B
SIZEFP164-BITRUNS ON (4-BIT)
1B2 GB
~1 GB
A phone
7B14 GB
~4–5 GB
A normal laptop
70B140 GB
~40 GB
A workstation
405B810 GB
~230 GB
A multi-GPU server
Fewer bits per number = quantization, the same idea as in your ADC.
Recap · Cost · Oct 2026

Why it is cheap, and what it really costs

YOU RENT A SLICE
One reply uses the GPUs for milliseconds to a few seconds.
THEY SHARE IT
The same GPUs serve a very large number of users at once.
ECE VIEW
Time-division multiplexing on one trunk line.
ONE CHAT MESSAGE · SONNET 5.5
in  1,000 tok × $2/1M  = $0.002
out  500 tok × $10/1M = $0.005
$0.007 ≈ 67 paise
Rate used: $1 = ₹95. A token is a piece of a word.
App plans (ChatGPT Plus, Claude Pro): about $20 a month, flat fee for the same models.
Output costs more than input. Free tiers exist — we use one in the lab.
Recap · What happens when you type

What happens when you type into ChatGPT

01 · YOU
You type a question
What is a MOSFET?
→
02 · INTERNET
The text goes to a server
Your phone sends it to the company’s data centre.
→
03 · DATA CENTRE
A model runs on GPUs
Large computers read your text and start the reply.
→
04 · BACK TO YOU
The reply comes word by word
A MOSFET is a voltage-controlled
Your phone does not think. It only sends your text and shows the reply. The work happens on a model far away.
Recap · Shells

Chat apps are shells around a model

When you talk to ChatGPT you are talking to a model. ChatGPT is the app wrapped around it. The model is the brain.

Recap · What is in front of you

What is actually in front of you

YOU SEE
The shell
chatgpt.com, claude.ai, the Gemini app — text box, history, login, buttons.
→
SENDS
A request
Your text, plus the conversation so far, over the internet.
→
DOES THE WORK
The model
A file of learned numbers, running on someone else’s GPUs.
The model dropdown at the top of the chat window? That is you swapping the brain inside the shell.
Recap · Shell and model

The app is a shell. The model does not remember.

SHELL · chatgpt.com
text box · history · login
MODEL
the brain
GPT · Claude · Gemini
Each send re-sends the whole chat:
send 1
m1
send 2
m1r1m2
send 3
m1r1m2r2m3
YOU PAY PER TOKEN · IN AND OUT
Sonnet 5.5: $2 in, $10 out per 1M tokens
One chat message ≈ 67 paise
Recap · Three ways in

Three ways to reach a model

A · THE COMPANY’S APP
Open the website or app
chatgpt.com
claude.ai
gemini.google.com
Easiest. You use it today.
B · AN API
Call it from your own code
Your program sends text to the company’s server and gets the reply back. You pay per use.
Today’s lab uses this door.
C · RUN IT LOCALLY
Download the weights
The model file runs on your own laptop. No internet needed.
Only possible with open-weight models.
Door C only works if the maker gives you the file. That is what “open” and “closed” mean.
Recap · Openness and access

Who gives you the file?

CLOSED
You rent access
GPT · Claude · Gemini
doors A · B
OPEN WEIGHT
You get the numbers
Llama · Qwen · DeepSeek
doors A · B · C
OPEN SOURCE
You get the recipe too
weights + data + code · rare
doors A · B · C
Door C only works with open weights. The lab uses door B, so closed models are fine.
Recap · The main makers · Oct 2026

Who makes which model, and where you use it

COMPANY
MODEL FAMILY
OPEN?
WHERE YOU USE IT
OpenAI
GPT-6 (Luna, Sol, Astra)
Closed
ChatGPT
Anthropic
Claude Haiku, Sonnet, Opus 5.5 · Fable 5.1
Closed
claude.ai, Claude app
Google
Gemini 4 Argon, Gemini Flash · Gemma 4 is open
Closed
Gemini app
Meta
Muse Spark · Llama, Muse Glimmer
Mixed
Meta AI, WhatsApp, Instagram
xAI
Grok 4.7
Closed
grok.com, X
DeepSeek
DeepSeek V4 (Pro, Flash)
Open weight
DeepSeek app
Alibaba
Qwen3.8
Open weight
Qwen app
Mistral
Mistral Medium 3.5, Mistral Large
Open weight
Le Chat
Moonshot
Kimi K3
Open weight
kimi.com
Version numbers change every few months. Learn the pattern: maker → family → open or closed → app.
Recap · More doors · Oct 2026

Apps where you pick the model yourself

Perplexity
Search with sources. Paid plans let you pick GPT, Claude or Gemini.
OpenRouter
One account, hundreds of models from many makers. Has a chat page.
T3 Chat
A fast chat app with a long model list.
Poe
Chat with many models and bots in one app.
GitHub Copilot
Coding help in your editor. Model picker: Claude, GPT, Gemini, Grok and more.
Cursor
A code editor built around AI. You choose the model.
LM Studio · LOCAL
A chat app on your own laptop. You pick an open-weight file and it runs offline. Door C.
Same models, different shells. The shell is a choice. So is the model.
Recap · Hallucination

A model will invent a datasheet value and sound completely sure

Today you only need to see it happen. Why it happens comes in a later lecture — and it is not a bug that someone forgot to fix.

THE RULECheck every number, part number and citation against the datasheet or a real source.
Why · AI is not optional

AI is not optional

Almost every task you do can be made faster or better with AI. It has become a built-in part of how work gets done.

Why · Where AI already sits

AI is already inside everyday work

Writing & email
Drafts, rewrites, summaries of long threads.
Coding
Writes, explains and debugs code, including firmware.
Search
Answers with sources instead of ten blue links.
Design
Diagrams, slides and images from a description.
Data analysis
Cleans a CSV of lab readings and plots it.
Circuit & chip design
PCB auto-routing, layout and verification help in EDA tools.
Documentation
Reads a 400-page datasheet and finds the register you need.
Meetings
Transcribes, then lists the decisions and action items.
Study
Explains a topic at your level, then quizzes you on it.
Why · Beyond ECE

It is in every field, and in your day

01
Medicine
Reads X-rays and eye scans to flag disease early.
02
Agriculture
A phone photo of a leaf identifies the crop disease.
03
Finance
Flags a fraud card payment in milliseconds.
04
Maps
Predicts traffic and your arrival time.
05
Phone cameras
Night mode and portrait blur are computed by a network.
06
Translation
Live captions and translation between dozens of languages.
You probably used AI today before this class started.
Why · Jobs

Jobs already ask for it

CORE ECE
VLSI and EDA
Chip-design job posts now list Python, scripting and AI tools next to Cadence and Synopsys skills. The EDA tools themselves ship AI features.
CORE ECE
Embedded and firmware
Teams use coding agents to write drivers, tests and docs. You are expected to check what the agent wrote.
IT AND SERVICES
TCS, Infosys, Wipro …
They train freshers and staff in generative AI and say these skills are hard to find.
EVERY ROLE
The interview question
“How do you use AI in your work?” A clear answer with one real example puts you ahead.
Knowing the AI words is not the skill. Using AI to get work done is.
Why · You can't skip it

You can’t skip AI

AI is the new internet: a personal-computer moment. ECE already depends on computers and the internet. It will depend on AI the same way.

1980s
Personal computer
Circuit simulation and CAD moved onto your desk.
1990s – 2000s
Internet
Datasheets, forums and open-source tools a search away.
NOW
AI
A tool that reads, writes, codes and designs with you.
So: how do you actually use it?
3.0 · Practical AI

Practical AI

Knowing the words is not enough. You need to do things with it.

3.1 · Practical AI · Two skills

Two different things people call “using AI”

A · USE AI
AI helps you get work done
You→ AI app→ your report, code, answer
Build, write, code, research, learn. ChatGPT, Claude, coding agents (Claude Code, Codex, Cursor), deep research.
Skill: asking well and checking the result
B · BUILD AI IN
Your app, with a model inside
User→ your app or agent→ API → model
Your program calls a model and uses the reply: a chatbot inside your app, or your own small agent with tools.
Skill: writing code that calls a model
Very different skills. Today we focus on B.
3.1 · Practical AI · A first

You are probably already doing A

Images
posters, diagrams, slides
Writing
emails, reports, summaries
Research
answers with sources
Spreadsheets
AI in Excel and Sheets: formulas, charts, cleaning data
A · USE AI TOOLS
Very practical. Taught properly later.
You may already have hands-on experience.
→A can
build B
later
B · BUILD AI IN
Today: by hand, with code.
So you understand what is inside.
Today I show you B by hand. Later you will build B through A: a coding agent writes the app for you.
3.2 · Build AI in · The model

A model on its own: text in, text out

IN
Text
“What resistor for a red LED on 5 V?”
→
MODEL
Predicts text
A file of learned numbers.
→
OUT
Text
“Use about 150 Ω.”
On its own it cannot search, run code, open a file or change anything.
3.2 · Build AI in · One call

Calling a model = one request, one reply

YOUR PROGRAM
Sends a request
Your text, over the internet.
→
PROVIDER
The model runs
On their GPUs.
→
YOUR PROGRAM
Gets a reply
The model’s text comes back.
This round trip is one API call. Everything in B is built from API calls.
3.3 · Build AI in · Agent

An agent = calling the model in a loop

A tool = a normal function in your program. The model can only ask for it.
Call the model It asks for a tool Your code runs it Result goes back in Answers in text? Stop.
Same API call as before, again and again. Claude Code and Codex are this same loop.
3.4 · Build AI in · API calls

To do B, your code makes API calls

1 · YOUR PROGRAM
Builds a request
→
2 · HTTP REQUEST
your key
the model name
the messages
→
3 · PROVIDER’S ENDPOINT
Runs the model
→
4 · REPLY (JSON)
Your program uses it
show it, or run a tool
That is all ChatGPT, Claude Code and our lab apps do underneath.
3.5 · Add AI to your app

What you need to add AI to your app

Five parts, then tools. One idea per slide. Then you build it in the lab.

3.5 · Add AI to your app · The parts

Five parts: provider, key, endpoint, model, your code

⑤
YOUR CODE
app.py
Builds the request and sends it.
→
THE REQUEST
③ to the endpoint URL
② with your API key in the header
④ the model name + your messages
→
①
PROVIDER
Runs the model
On its GPUs. Sends back the reply as JSON.
← reply (JSON) comes back to your code
① Provider
runs the model
② API key
proves it is you
③ Endpoint
the URL you call
④ Model name
which brain
⑤ Your code
sends the request
3.5 · Add AI · ① Provider

A provider runs models and rents them to you

DATA CENTRE
GPUs + the model
→
HTTP ENDPOINT · ON THE INTERNET
https://…/v1/chat/completions
Anyone with a key can send a request.
→
YOU
Your code
From any laptop.
MAKERS · serve their own models
OpenAI · GPT
Anthropic · Claude
Google · Gemini
HOSTS AND ROUTERS · serve other makers’ models
Groq · runs open models on its own fast chips
OpenRouter · one key, forwards to many providers
Vercel AI Gateway · one key, many makers · our lab
They bill per token, in and out. Remember: one chat message on Sonnet 5.5 ≈ 67 paise.
3.5 · Add AI · ② API key

The API key tells the provider it is you

sk-vgw-7Hq2Lr9…X4c9xLp
A long secret string. The provider gives it to you.
(This one is fake.)
EVERY REQUEST
Carries the key in a header
Authorization:
Bearer sk-vgw-7Hq2…
→
PROVIDER
Looks up the key
Finds your account.
→
SO IT CAN
Bill you
Apply your limits
Block you
No key, wrong key, or empty account: the provider refuses the request.
3.5 · Add AI · ② Keep the key secret

Anyone with your key can spend your money

KEEP IT
✓in a .env file on your laptop
✓.env listed in .gitignore
✓read by config.py, never typed
NEVER PUT IT
✕in your code
✕in git or GitHub
✕in a screenshot
✕on WhatsApp or email
Leaked? Delete the key in the provider’s dashboard and make a new one. Do it now, not tomorrow.
3.5 · Add AI · ③ Endpoint + ④ model

One URL. The model is just a string.

③ ENDPOINT · THE SAME FOR EVERY MODEL
https://ai-gateway.vercel.sh/v1/chat/completions
④ MODEL · ONE STRING IN THE REQUEST BODY
"model": "anthropic/claude-haiku-5.5"
Anthropic · cheap and fast
"model": "openai/gpt-6-luna"
OpenAI
"model": "google/gemini-3.8-flash"
Google
Example names, Oct 2026. Copy the exact string from the provider’s model list.
Switching models = changing one string. Same URL, same code. In the lab it is the MODEL= line in .env.
3.5 · Add AI · The request

Anatomy of a request

POST https://ai-gateway.vercel.sh/v1/chat/completions1
Authorization: Bearer <your API key>2
{
"model": "anthropic/claude-haiku-5.5",3
"messages": [4
{"role": "user", "content": "What is a MOSFET?"}
],
"tools": [ ... ],5
"temperature": 0.7,6
"max_tokens": 3007
}
1
URL
where it goes: the endpoint
2
Header
who you are: the API key
3
model
which brain
4
messages
the conversation: a list of {role, content}
5
tools · optional
functions it may ask for
6
temperature · optional
0 = same answer each time, 1 = more varied
7
max_tokens · optional
stop after this many tokens, limits cost
Your code builds exactly this. Soon you will see how.
3.5 · Add AI · The messages list

Four roles. The list is the memory.

messages = [
1 {"role": "system", "content": "You run the ECE lab store."},
2 {"role": "user", "content": "How many LM35 are left?"},
3 {"role": "assistant", "tool_calls": [check_stock]},
4 {"role": "tool", "content": "LM35 sensor: 4"},
5 {"role": "assistant", "content": "4 are left."},
6 {"role": "user", "content": "Issue 2 to me."},
]
systemThe job. Your instructions. Goes first.
userWhat the person typed.
assistantWhat the model said earlier: text, or a request for a tool.
toolThe result of a tool your code ran.
Order = time order. The model sees only this list, and you decide what goes in.
3.5 · Add AI · The response

Anatomy of a response

{
"choices": [
{"message": {
"role": "assistant",
"content": "A MOSFET is a voltage-controlled switch.",1
"tool_calls": null2
}}
],
"usage": {"prompt_tokens": 14,3
"completion_tokens": 9, "total_tokens": 23}
}
1
The textchoices[0].message.content
2
A tool requestchoices[0].message.tool_calls: a list when it wants a tool. Then content is empty.
3
Tokens → costusage: tokens in and out. This is your bill.
Your code reads the text, checks for tool calls, and can log the tokens.
3.5 · Add AI · Tools

A tool is a normal function in your code

def ohms_law(voltage, resistance):
return voltage / resistance
# current in amperes
1You write it, in Python.
2It runs on your computer, not in the model.
3The model only gets its name and description.
read_file
returns the text of a file
add_task
adds a task to your to-do app
set_relay
switches a relay on your board
The model cannot run anything. It can only ask for a tool.
3.5 · Add AI · Tools

You describe the tool in the request

"tools": [{
"type": "function",
"function": {
"name": "ohms_law",1
"description": "Current (A) from voltage (V)"
"and resistance (ohm)",2
"parameters": {"type": "object", "properties": {3
"voltage": {"type": "number"},
"resistance": {"type": "number"}}}
}
}]
1
namewhat the model asks for
2
descriptiontells the model when to use it
3
parametersthe inputs and their types
The model sees only this. It never sees your Python code.
Same request as before, plus the "tools" field. It goes with every call.
3.5 · Add AI · Tools

The model asks, your code runs it

Your code Model ① question + "tools" “How much current through 220 Ω at 5 V?” ② "tool_calls": ohms_law {"voltage": 5, "resistance": 220} not text: a request to run the tool ③ PYTHON RUNS IT ohms_law(5, 220) = 0.0227 ④ + {"role": "tool", "tool_call_id": "…", "content": "0.0227"} send back the model's tool_calls message + this tool message ⑤ “About 22.7 mA.” (text, so done) API call 1ask API call 2answer
Two API calls for one question. Python did the maths; the model wrote the words.
3.5 · Add AI · Tools

Tools + a loop = an agent

ONE TOOL CALL · LAB STEP 5
One round trip
Ask → the model asks for a tool → your code runs it → send the result back → text answer. 05_tool.py
TOOLS + A LOOP · LAB STEP 6
Repeat until it answers in text
Same round trip in a while loop, with many tools. The agent circle from before. 06_mini_app.py
call model → tool_calls? run them, add results → call again → … → text: stop
You build exactly this in the lab. No magic: API calls + your functions + a loop.
Now the code

Now the code, step by step

Six short Python files. Each adds one idea: one call → no memory → memory → system prompt → one tool → a small agent.

Lab · Today's practical

From one API call to an app with AI inside

STEPS 1–6
Six short Python files
One call → no memory → memory → system prompt → one tool → a small agent.
EXERCISE 1
Your own ChatGPT
A Flask web page with a chat box. Your server keeps the messages.
EXERCISE 2
An app without AI
A Flask to-do list: add, complete, delete. Saved in a JSON file.
EXERCISE 3
Add AI to it
An “Ask AI” box. The AI uses your app's functions as tools.
▶ Chat app</> Code
▶ To-do app</> Code
▶ To-do + AI</> Code</> What changed
Lab · Setup

Get a free API key, and keep it secret

FREE TIER
Google AI Studio
aistudio.google.com · OpenAI-compatible endpoint
FREE TIER
Groq
console.groq.com · very fast open models
SOME FREE MODELS
OpenRouter
openrouter.ai · many makers, one key
Make a key, then fill in .env.
The three lines are parts ②, ③ and ④. config.py reads them. Add .env to .gitignore.
# .env (this file stays on your laptop)
API_KEY=paste-your-key-here
URL=https://.../chat/completions
MODEL=model-name-from-the-site
Lab · Step 1 of 6
</> View code

Send one request, print the answer

import requests
from config import API_KEY, URL, MODEL
question = input("Ask a question: ")
response = requests.post(
URL,
headers={"Authorization": "Bearer " + API_KEY},
json={"model": MODEL, "messages": [{"role": "user", "content": question}]},
)
data = response.json()
print("AI:", data["choices"][0]["message"]["content"])
print("Tokens used:", data["usage"]["total_tokens"])
Sends
the model name + one user message
With
your key in the header
Gets
JSON: the text and the token count
Lab · Step 2 of 6
</> View code

It does not remember

headers = {"Authorization": "Bearer " + API_KEY}
first = {"model": MODEL, "messages": [{"role": "user", "content": "Hi, my name is Aman."}]}
reply = requests.post(URL, headers=headers, json=first).json()
print("Call 1:", reply["choices"][0]["message"]["content"])
second = {"model": MODEL, "messages": [{"role": "user", "content": "What is my name?"}]}
reply = requests.post(URL, headers=headers, json=second).json()
print("Call 2:", reply["choices"][0]["message"]["content"])
Call 1: Nice to meet you, Aman!
Call 2: I don’t know your name.
Each request stands alone. The model keeps nothing between calls.
Lab · Step 3 of 6
</> View code

Keep a list, send all of it

messages = []
while True:
text = input("You: ")
if text == "exit":
break
messages.append({"role": "user", "content": text})
response = requests.post(URL, headers={"Authorization": "Bearer " + API_KEY},
json={"model": MODEL, "messages": messages})
answer = response.json()["choices"][0]["message"]["content"]
messages.append({"role": "assistant", "content": answer})
print("AI:", answer)
turn 1 · 1 message
u1
turn 2 · 3 messages
u1a1u2
turn 3 · 5 messages
u1a1u2a2u3
It remembers because you send the whole list every time. Each turn sends more tokens.
Lab · Step 4 of 6
</> View code

A system message gives it a job

question = input("Ask the lab assistant: ")
messages = [
{"role": "system", "content": "You are a helpful ECE lab assistant. "
"Answer in 3 short lines. Use simple words."},
{"role": "user", "content": question},
]
response = requests.post(
URL,
headers={"Authorization": "Bearer " + API_KEY},
json={"model": MODEL, "messages": messages},
)
print("AI:", response.json()["choices"][0]["message"]["content"])
The user never sees it, but it changes every answer. Try: “Answer only in Hindi.”
Lab · Step 5 of 6
</> View code

One tool: the model asks, your Python runs it

# Call 1: the model replies with a tool call, not with text
reply = requests.post(URL, headers=headers, json={"model": MODEL, "messages": messages, "tools": tools}).json()
message = reply["choices"][0]["message"]
call = message["tool_calls"][0]
args = json.loads(call["function"]["arguments"])
result = ohms_law(args["voltage"], args["resistance"]) # OUR Python runs it
# Call 2: send the tool result back and get the final answer
messages.append(message)
messages.append({"role": "tool", "tool_call_id": call["id"], "content": str(result)})
reply = requests.post(URL, headers=headers, json={"model": MODEL, "messages": messages, "tools": tools}).json()
print("AI:", reply["choices"][0]["message"]["content"])
1 · YOU
Ask with tools
“5 V across 220 Ω?”
2 · MODEL
Asks for the tool
ohms_law(5, 220)
3 · PYTHON
Runs it
0.0227
4 · MODEL
Answers
“About 22.7 mA.”
Lab · Step 6 of 6
</> View code

Tools + a loop = a small agent on your data

while True: # keep calling until the model stops asking for tools
response = requests.post(URL, headers={"Authorization": "Bearer " + API_KEY},
json={"model": MODEL, "messages": messages, "tools": tools})
reply = response.json()["choices"][0]["message"]
messages.append(reply) # the model's reply goes into the history too
if not reply.get("tool_calls"):
break
for call in reply["tool_calls"]:
args = json.loads(call["function"]["arguments"])
result = functions[call["function"]["name"]](**args)
messages.append({"role": "tool", "tool_call_id": call["id"], "content": str(result)})
print("AI:", reply["content"])
Your data: stock = {"LM35 sensor": 4, …}
Your tools: check_stock · issue_item
“Give 2 LM35 to Riya, then tell me what is left.”
The agent loop from the theory, on your own data. Claude Code is this, with more tools.
Lab · Exercise 1
▶ Open chat app</> View code

Build your own ChatGPT

BROWSER
Chat page
A text box and the messages.
⇄message
FLASK · YOUR CODE
app.py
Holds the key and the messages list. Calls the API.
⇄API call
MODEL API
Google · Groq · OpenRouter
Returns the next reply.
Files: app.py (Flask) and templates/index.html (the chat page).
The key stays on the server. The browser never sees it.
This is all ChatGPT is — plus a lot of polish.
Lab · Exercise 2
▶ Open to-do app</> View code

An app without AI: a to-do list

MY TASKS
New task…
Add
Finish op-amp lab readings✕
Buy 150 Ω resistors✕
Read the 555 timer datasheet✕
YOUR FUNCTIONS · app.py
def add_task(title): ...
def list_tasks(): ...
def complete_task(id): ...
def delete_task(id): ...
Saved in tasks.json, so tasks stay after a restart.
No AI yet. Remember these function names — next they become tools.
Lab · Exercise 3
▶ Open to-do + AI</> View code</> What changed

Add AI to that app: your functions become tools

USER
Ask AI box
Types a request in plain words.
→
MODEL
Decides
Which tool, with which values.
→
TOOLS · YOUR CODE
add_task · list_tasks · complete_task
→
DATA
tasks.json
The list updates on screen.
“Add tasks for my ECE lab report due Friday, split into steps.”
“What is still pending?”
The model only asks. Your functions change the data.
Lab · Use AI to build

You can build all of this with a coding agent

PROMPT FOR A CODING AGENT
Goal: in my Flask to-do app (app.py, tasks.json), add an “Ask AI” box.
The AI must use my functions add_task, list_tasks and complete_task as tools.
Constraints: Python + Flask + requests only. Read API_KEY, URL, MODEL
from .env. Use the OpenAI-style chat/completions API with “tools”. Keep it short.
Check: run it, ask “add 3 tasks for my lab report”, and show me
that the tasks appear in tasks.json.
Read the diff
Know what it changed.
Run it yourself
Do not trust “it works”.
Explain it
If you cannot, ask it to teach you.
Take this home

Use AI to build.
Build AI into what you make.

Both skills, from today: you used AI to write code, and you put a model inside your own app with your own tools.