Data Sense · Live Workshop

AI Fundamentals
in 3 Hours

From your first LLM API call to a working agent loop. No 20-hour course. No theory dump. Everything else in AI builds on this.

LLM API calls Messages & system prompts Tokens & cost Structured JSON RAG Tool calling Agent loop
Built end to end with LangChain learn one interface, use every model
When
Sunday, 13 September · 8:00–11:00 AM IST
Format
2 × 1.5 hour classes · hands-on
Ground rules

What this workshop is, and what it is not

Setting expectations so you know exactly what you walk out with.

This is
  • Hands-on. You run every cell with me, in a notebook.
  • Provider-agnostic. One interface. OpenAI, Claude, Gemini, or a local model.
  • The 20% that explains 80% of every AI product you will ever build.
  • A working agent in your own hands by 11:00 AM.
This is not
  • Transformer maths. No attention formulas, no backprop.
  • Model training. We are not building an LLM. Nobody in your job will ask you to.
  • A tour of five frameworks. We learn one of them, LangChain, properly instead.
  • A finished product. It is the foundation. The roadmap at the end shows what sits on top.

The one belief to leave with: an LLM is a function you call over HTTP. Everything sophisticated in AI is ordinary software engineering arranged around that one function call.

The landscape

Three layers. You work on exactly one of them.

Almost every "AI job" argument on the internet is two people talking about different layers.

Layer 1. Model builders Train the foundation models. Transformers, GPUs, pre-training, RLHF, scaling laws. OpenAI · Anthropic · Google DeepMind · Meta · Mistral · a handful of labs worldwide ~0.1% of AI jobs Layer 2. AI engineers · you are here Build and ship software on top of those models. Prompts, RAG, tools, agents, evals, latency, cost, guardrails. Every product company: fintech, health, retail, SaaS, consulting, internal platform teams requests → API → response → your application logic ~90% of AI jobs Layer 3. Operators & power users Use AI products well. Prompting, workflow automation, no-code tools, internal enablement. Marketing, ops, analysts, support, founders, valuable, but not an engineering role growing everyone else

Today is Layer 2, from the ground up. Layer 1 is fascinating and almost certainly not your job.

The biggest misconception

You are not building LLMs. You are calling them.

Two completely different disciplines that share one word.

Building a model
15T tokens of text 50,000 GPUs 3 months $100M+ weights .safetensors
  • Needs: transformers, CUDA, distributed training, RLHF
  • Done by: research labs with nine-figure budgets
  • Output: a model file
vs
Using a model: your job
your code 15 lines the model someone else's HTTPS request JSON response
  • Needs: Python, HTTP, JSON, product sense
  • Done by: every company shipping an AI feature
  • Output: a product people use

A useful analogy: you do not build a database engine to become a backend engineer. You learn SQL, connection pooling, indexes, and schema design. Same relationship here.

Who does what

The roles around an AI product

Titles change between companies. The work does not. Find yourself here.

1 AI Engineer

Ships product features powered by models. Prompts, RAG, tool calling, agents, evals, latency and cost.

Today's target role. Also called: LLM Engineer, GenAI Engineer, Applied AI Engineer.

2 ML Engineer

Trains and serves task-specific models. Feature pipelines, training jobs, model registries, drift monitoring.

Still very much hiring, fraud, ranking, forecasting, recsys. Different toolchain from AI engineering.

3 Research Scientist

Invents new architectures and training methods. Publishes. Builds the models in Layer 1.

Usually PhD-track, concentrated in a few dozen labs. The rarest of these roles.

4 Data Scientist

Answers business questions with data. Increasingly also owns evals and offline quality measurement for AI features.

Shortest hop into AI engineering, you already have Python and evaluation instincts.

5 Forward Deployed Engineer

Sits with the customer and builds the integration in their environment. Half engineer, half consultant.

Exploding right now. Same skills as an AI engineer, plus client-facing nerve.

6 AI Product Manager

Decides what to build and what "good" means. Owns the eval set, the failure budget, and the risk posture.

Needs to understand tokens, latency and hallucination, not to write the code.

Also in the room: platform / infra engineers who run the gateways and observability, data engineers who feed the retrieval layer, and security folks who own prompt-injection and data-leak review. AI is a team sport.

The comparison everyone asks for

AI Engineer vs ML Engineer

Same industry, opposite starting point. One starts from a trained model, the other produces one.

AI EngineerML Engineer
Starts withA model that already existsA dataset and a metric
Core skillContext engineering: what you put in the promptFeature engineering: what you put in the model
Daily toolsLangChain · vector DB · tracing · evalspandas · sklearn · PyTorch · MLflow
Iteration loopMinutes, edit prompt, rerun evalHours to days, retrain, revalidate
Hard partReliability of a non-deterministic systemAccuracy and generalisation
Costs money atInference time, every single requestTraining time, mostly up front
Entry barrierWeeks, if you can already codeMonths, statistics plus MLOps

They overlap in production. Both care about latency, cost, monitoring, rollback and data privacy. The MLOps discipline transfers almost completely.

Most real systems use both. A classifier routes the request, an LLM handles the open-ended part. Knowing both makes you unusually valuable.

Your path in

Where people come from, and what they bring

Nobody starts from zero. Find your row and see what you are actually missing.

Software / Backend Engineer has: APIs, deployment, system design needs: prompting, evals, non-determinism Data Scientist / Analyst has: Python, metrics, experiment design needs: API engineering, shipping to production ML Engineer has: modelling, MLOps, serving needs: unlearning "train a model" as the reflex QA / Support / Ops has: edge cases, real user pain, process needs: Python, then evals are your superpower Student / Career switcher has: time, and no habits to unlearn needs: Python, HTTP, git, then this workshop twice AI Engineer ships LLM-powered features prompts · RAG · tools agents · evals · cost
Reality check

What an AI engineer actually does all day

Roughly what the work splits into. Notice how little of it is "AI".

Plumbing & product code~40%

APIs, queues, auth, retries, streaming to a UI, database work. Ordinary engineering.

Context engineering~25%

Deciding what goes into the prompt: instructions, retrieved documents, tool results, history.

Evaluation & debugging~25%

Why did it answer wrong on this input? Building the test set that catches it next time.

Model & cost tuning~10%

Cheaper model here, caching there, trimming the context. Where the margin lives.

The uncomfortable truth

Zero percent of the day is spent on model architecture. The hard, valuable part is making a probabilistic component behave inside a deterministic product.

Which is good news

Every hour you have already spent learning to write clean, testable, observable software counts directly toward this role.

The skill that separates people

Not prompting. Evals. Anyone can get a demo working once. Knowing whether your change made it better across 200 cases is the job.

The next three hours

What we build, in order

Each step is the previous step plus exactly one new idea. Nothing is skipped.

1 LLM call messages · roles system prompt 2 Tokens & cost context window what you pay for 3 Structured JSON text → data safe to parse 4 RAG chunk · embed retrieve · ground 5 Tool calling the model asks your code acts 6 Agent loop it until the job is done CLASS 1 · 90 MIN CLASS 2 · 90 MIN

Every single one of these is the same HTTP call with more structure around it. That is the whole secret.

Step 1 · The mental model

In your world, an LLM is just an API

You send JSON over HTTPS. You get JSON back. That is the entire interface.

Your application Python · Node · anything model = init_chat_model( "openai:gpt-4.1-mini") model.invoke(messages) POST /v1/chat/completions your instructions + the conversation so far 200 OK · { "choices": [ … ] } generated text + token usage Provider GPUs you will never see the model weights someone else's problem No GPU on your machine. No model download. No maths. If you have ever called a REST API, you already know 80% of this.
Step 1 · The one thing to learn

Every provider is different. LangChain isn't.

Learn one interface today and it carries you all the way to agents, and on to whatever model wins next year.

Without a framework
# OpenAI r.choices[0].message.content r.usage.prompt_tokens   # Anthropic r.content[0].text r.usage.input_tokens   # Google r.candidates[0].content.parts[0].text r.usage_metadata.prompt_token_count

Three SDKs. Three response shapes. Three names for the same number. Switching providers means a rewrite. So teams don't, even when it would halve the bill.

With LangChain
model = init_chat_model("openai:gpt-4.1-mini") reply = model.invoke(messages)   reply.content reply.usage_metadata["input_tokens"]   # switch provider = change the string "anthropic:claude-sonnet-4-5" "google_genai:gemini-2.0-flash" "ollama:llama3.2" # runs locally

One shape. And the same invoke works on tools, retrievers, chains and agents, so the rest of this morning is the same verb, over and over.

Same verb everywhere

invoke · batch · stream on models, tools, retrievers, agents. Learn it once.

Batteries included

Splitters, embeddings, 20+ vector stores, the agent loop, memory, approval gates. Already written.

It grows with you

Same objects carry into LangGraph for custom control flow and LangSmith for evals.

Not a black box

We will print the exact JSON it sends. A framework you can see through is a tool, not magic.

Step 1 · Anatomy

Every LLM call has the same five parts

Learn these five once. They are identical for every model LangChain supports.

the request
from langchain.chat_models import init_chat_model   model = init_chat_model( "openai:gpt-4.1-mini", temperature=0.2, max_tokens=300, )   reply = model.invoke([ SystemMessage("You are a terse tutor."), HumanMessage("What is an API?"), ])
the response
reply.content # the text reply.usage_metadata["input_tokens"] # what you sent reply.usage_metadata["output_tokens"] # what it wrote reply.response_metadata["finish_reason"] # why it stopped
1 model

provider:model. Swapping this one string changes cost, speed, quality, and even the vendor.

2 messages

An ordered list passed to invoke. This is the conversation. Everything the model knows this turn is in here.

3 SystemMessage

Standing orders: role, tone, rules, format. Set once, applies to every turn.

4 HumanMessage

The actual request for this turn. In a real product, the only part that comes from your user.

5 knobs

temperature randomness, 0 is focused. max_tokens a hard ceiling on the reply, and on the bill.

Step 1 · Messages

Three roles, and who is allowed to write them

Getting this wrong is the root cause of most "the AI ignored my instructions" bugs.

SystemMessagewritten by you, the developer

"You are a support agent for Acme Bank. Never give financial advice. Answer in under 80 words."

HumanMessagewritten by your end user

"My card got declined at a petrol pump this morning. Why?"

AIMessagewritten by the model

"Declines at fuel pumps are usually a pre-authorisation hold…"

Append it back into the list to continue, or let a checkpointer do it for you.

Danger

Anything a user types arrives as a user message. If you paste user text into your system prompt, you have handed them the steering wheel. That is prompt injection, and it is the number one AI security bug.

The mental model

The system prompt is the job description. The user message is today's ticket. Never let the ticket rewrite the job description.

Practical rule: system prompt is a constant in your code or a versioned file. If it is being built by string-concatenating user input, stop and redesign.

Step 1 · The surprise

The model has no memory. None.

Every call is the first call. ChatGPT feels like it remembers because the app resends the whole history each time.

TURN 1 system: "You are a tutor." user: "My name is Priya." sent TURN 2. WRONG system: "You are a tutor." user: "What is my name?" → "I don't know your name." TURN 2. RIGHT system: "You are a tutor." user: "My name is Priya." assistant: "Hi Priya!" user: "What is my name?" → "Priya." Consequence: conversation history is your job, not the model's Store the messages list. Append the assistant reply. Resend the whole thing next turn. And because you resend everything, a long chat costs more per turn than a short one. The bill grows with the conversation.
Step 2 · The unit of everything

Models do not read words. They read tokens.

A token is a chunk of characters. Roughly ¾ of a word in English. It is the unit you are billed in and limited by.

plain English
Data Sense is teaching AI fundamentals. 7 tokens · 38 characters
rare word
unbelievable 3 tokens for one word, common words are cheap, unusual ones are not
Hindi
टोकनाइज़ेशन 6 tokens for one word, common Hindi words split 3 ways where English takes 1
Why you care, money

You pay per token, in and out. Trimming a bloated prompt is a real cost saving, not a micro-optimisation.

Why you care, limits

The context window is measured in tokens. Exceed it and the request fails outright.

The number that matters

The same message in Hindi costs about 1.2–1.7× more than in English. Real, but smaller than the word above suggests, measure, don't assume.

Step 2 · The hard limit

The context window is the model's desk

Everything the model can see this turn must fit on the desk at once. Nothing else exists.

One request, filling up 128,000 token window
System promptrules, persona, output format~600
Conversation historyevery previous turn, resent~2,000
Retrieved documentsthe RAG chunks, usually the biggest slice~4,300
Room for the answeroutput shares the same budget~1,500
Unused headroomthe rest
Windows keep growing

Older models: 4K–8K. Common today: 128K. Frontier models: 1M tokens: a few hundred pages in one request.

Bigger is not free

A 1M-token window does not mean you should fill it. You pay for every token, latency rises, and accuracy drops on facts buried in the middle.

The job this creates

Context engineering: choosing the smallest set of tokens that reliably produces the right answer. This is the core craft of the role.

Step 2 · The bill

Doing the arithmetic once, properly

This is the calculation that decides whether your AI feature ships or gets cancelled.

Published rates, per 1M tokens
ModelInputOutput
gpt-4.1-mini$0.40$1.60
gpt-4.1-nano$0.10$0.40
gpt-4.1$2.00$8.00
gpt-5-mini$0.25$2.00
gpt-5$1.25$10.00
text-embedding-3-small$0.02

Output always costs more than input, generation is the expensive half. Rates move; the method below does not.

A support bot on gpt-4.1-mini
per conversation: 2,000 input + 400 output tokens   input 2,000 / 1,000,000 × $0.40 = $0.00080 output 400 / 1,000,000 × $1.60 = $0.00064 total = $0.00144

10,000 conversations / day

$14.40

per day

over a month

$432

per month

same load on nano

$108

per month · 4× cheaper

The lever nobody uses: most production traffic is simple. Route the easy 80% to the cheap model, the hard 20% to the expensive one, and your bill drops by more than half without anyone noticing.

Step 2 · The uncomfortable part

Same input, different output, by design

The model predicts a probability distribution over the next token, then samples from it.

prompt → "The capital of France is"

" Paris"
92%
" the"
4%
" a"
2%
" Lyon"
1%
…50k more
1%

It does this once per token, then feeds its own output back in and does it again. That loop is the whole of "generation".

temperature=0 take the top token

Focused and repeatable. Use for extraction, classification, routing, anything you parse. Still not a guarantee of identical output.

temperature=1 sample the distribution

Varied and creative. Use for brainstorming, copy, ideation. Never for anything downstream code depends on.

What this means for you

You cannot write assertEqual against an LLM. Testing shifts from exact match to graded evaluation over many cases. That shift is the real mental jump for engineers.

Step 3 · Text into data

Prose is unusable. Ask for JSON instead.

The moment an LLM feeds another system, you need a guaranteed shape, not a nicely written paragraph.

Unusablefree text
The customer seems quite upset about a delayed refund of around twelve thousand rupees. I'd treat this as high priority.

Now write the regex that pulls out the amount. Now handle 12,000, 12k, ₹12000. Now handle the day it answers in Hindi.

Usableschema-enforced JSON
{ "sentiment": "negative", "category": "refund_delay", "amount_inr": 12000, "priority": "high" }

Route it, store it, chart it, alert on it. It is just a dict. Your code never has to read English again.

Why not just ask politely for JSON? Because it works until it doesn't, a stray "Sure! Here's the JSON:" prefix breaks json.loads at 2 a.m. A schema is enforced during generation. Invalid JSON stops being unlikely and becomes impossible.

Step 3 · How you ask for it

One line turns a model into a typed function

Describe the shape in Pydantic, hand it to the model, get a real Python object back.

from pydantic import BaseModel, Field from typing import Literal   class Ticket(BaseModel): sentiment: Literal["positive", "neutral", "negative"] category: Literal["refund", "shipping", "payment"] amount_inr: int | None = Field(None, description="rupees, or null") priority: Literal["low", "medium", "high"]   triage = model.with_structured_output(Ticket)   ticket = triage.invoke(text) # a real Ticket object tickets = triage.batch(many) # …and it parallelises
Design it like an API contract

Enums instead of free strings, so it cannot invent a 14th category next Tuesday. Allow null so it can say "not present" rather than make something up.

The model reads your schema

Field names and descriptions are prompt engineering, not documentation. Name them descriptively and put the business rule in the description.

It is a runnable, like everything else

with_structured_output returns something with invoke, batch and stream the same verbs as the model, the retriever and the agent.

End of Class 1

You can now build a lot. Here is what still breaks.

Three failures you cannot prompt your way out of. Each one has a named solution, and those are Class 2.

Failure 1

It does not know your data

Your company policies, your product docs, last night's order table, none of it was in the training data. Ask about it and you get a confident, fluent, wrong answer.

solved byRAG
Failure 2

It cannot do anything

It cannot check today's price, send the email, query the database, or run the refund. It produces text. Text alone never changed anything in the real world.

solved byTool calling
Failure 3

It gets one shot

Real tasks take several steps, and step three depends on what step two returned. One call cannot look, decide, act, then look again.

solved byThe agent loop

Notice none of these are fixed by a better model. They are fixed by better engineering around the model. A smarter model still cannot read a database it was never shown.

Step 4 · Retrieval-Augmented Generation

RAG: look it up first, then answer

You are not teaching the model anything. You are pasting the right paragraph into the prompt, automatically.

1 · INDEXING. RUN ONCE, OFFLINE, WHEN DOCUMENTS CHANGE 2 · RETRIEVAL. RUNS ON EVERY SINGLE USER QUESTION Your docs PDFs · wiki · tickets Chunks ~500 tokens each Embedding model text → vector Vector store FAISS · Chroma pgvector · Pinecone [0.02, -0.41, …] vector + original text User question "what is our refund window?" Same embedding model must be identical nearest-neighbour search Top-k chunks the 3–5 closest Augmented prompt chunks + question stitched together LLM plain old step 1 call Grounded answer with a citation The last box is an ordinary LLM call. RAG is everything that happens before it.
Step 4 · Chunking

Why we cut documents up

Two reasons: a whole document will not fit, and retrieving a whole document buries the one line that mattered.

A 40-page handbook

~20,000 tokens. Too big for a prompt, and 99% of it is irrelevant to any one question.

Forty retrievable chunks

Two highlighted chunks answer the question. You send ~1,000 tokens instead of 20,000.

Size

300–800 tokens is the usual sweet spot. Too small loses the context around a fact; too large dilutes the match and wastes budget.

Overlap

Repeat ~10–15% of the previous chunk at the start of the next, so a sentence split across a boundary still survives in one piece.

Split on structure, not characters

Break on headings, paragraphs, then sentences. Cutting mid-table or mid-code-block is where most bad retrieval actually comes from.

Step 4 · Embeddings

Text goes in. Numbers come out.

An embedding model turns any piece of text into a fixed list of numbers. These are real vectors from text-embedding-3-small.

"refund"
"money back"
"wifi password"
You cannot read these

Stare at the numbers all day and you will learn nothing. No single dimension means "money" or "refund".

But you can measure them

The only question you ever ask is how far apart two of these are. That is the whole of semantic search.

Same model, always

Index with one embedding model and query with another and you get silent nonsense. No error, just bad results.

Step 4 · Embeddings

Words that mean the same thing land together

Thirteen real phrases, embedded for real, then squashed from 1,536 dimensions down to 2 so your eyes can see it.

Nothing here was hand-placed

Every dot sits where the real embedding put it. The clusters formed on their own, because the model learned that "money back" and "refund" mean nearly the same thing.

refunds and returns
delivery and shipping
payment methods
unrelated to any of it

Honest caveat: flattening 1,536 dimensions to 2 keeps only 31% of the real structure. The picture is a shadow of the real space, not the space itself.

Step 4 · Retrieval

Watch it actually retrieve

One real question, scored against the real Nimbus documents. These are the measured cosine similarities, not an illustration.

the question
"can I get my money back?"
The top 2 go into the prompt

Everything below the line is dropped. You are choosing what the model is allowed to see, and you are paying for every token you keep.

Look at the actual numbers

The winner scores 0.385. Not 0.95. Cosine scores in real corpora are low and close together, which is exactly why ranking matters more than any threshold you might be tempted to set.

And it is not perfect

Second place is "Shipping charges", which is the wrong section. The gap between 1st and 3rd is tiny. This is the near-miss that hybrid search and reranking exist to fix.

Step 4 · The demystifier

What actually reaches the model

Every RAG framework, no matter how many abstractions deep, ends up building this one string.

the final prompt, assembled
SYSTEM Answer using ONLY the context below. If the answer is not in the context, say "I don't know". Cite the source of every claim.   USER <context> [handbook.pdf p.12] Refunds are processed within 14 days of the return being received at our…   [policy.md #returns] Items must be unopened and returned within 30 days of delivery… </context>   Question: what is our refund window?
That is the whole of RAG

Retrieved text, pasted into the prompt, with an instruction to stay inside it. No fine-tuning, no model change, no magic.

The grounding instruction earns its keep

"Say I don't know" converts a confident hallucination into an honest miss. That one line is the difference between a demo and something you can put in front of customers.

Citations are free

Label each chunk with its source when you paste it in, and ask for the label back. Now every answer is checkable, which is what earns user trust.

Why build it by hand first

When a framework misbehaves later, you will know that somewhere inside it, a string like this one is being built, and you will go and print it.

Step 4 · Reality

RAG is easy to demo and hard to get right

Your first version will work. Here is where version two breaks, and what you turn to fix it.

Retrieval failures
  • The right chunk was never returned: the question and the document use different words
  • The answer was split across two chunks and neither one alone made sense
  • Top-k returned five chunks that all say the same thing
  • Exact identifiers, order IDs, error codes, which vectors are genuinely bad at
The knobs, in the order worth trying
  • Hybrid search: run keyword and vector search together. Biggest single win, almost always.
  • Rerank: retrieve 30 candidates, have a cheap cross-encoder pick the best 5.
  • Query rewriting: let the LLM rephrase a vague question before searching.
  • Better chunking: split on document structure, keep headings with their body.
  • Metadata filters: restrict by product, date or language before searching at all.

The diagnostic that saves you weeks: before touching the prompt, check whether the correct chunk was in the retrieved set at all. If it was not, this is a search problem, and prompt engineering cannot help you. If it was, and the answer is still wrong, now it is a generation problem.

Step 5 · Tools

A brilliant mind, locked in a room

RAG gave the model knowledge. It still has no hands.

What the model cannot do alone
  • Tell you today's date, or today's stock price
  • Look up order #48213 in your database
  • Do arithmetic reliably on large numbers
  • Send the email, issue the refund, book the slot
  • Search the web, read a file, call your API

It will happily produce text that looks like it did all of these. That is the danger.

What a tool actually is

An ordinary function in your codebase, plus a description the model can read.

def get_order_status(order_id: str) -> dict: """Look up an order's current status.""" return db.query("…", order_id)

You already know how to write this part. The only new idea is letting the model decide when to call it.

The human analogy: the model is the brain. Tools are the hands, the phone and the filing cabinet.

Step 5 · The round trip

The model never runs your code. It asks you to.

This is the one idea that unlocks agents. Read the arrows carefully. It is a conversation, not a callback.

YOUR CODE THE MODEL messages=[…] + tools=[get_order_status] 1 you send the question + the menu of tools finish_reason: "tool_calls" get_order_status({"order_id": "48213"}) 2 it replies with a request, not an answer YOU execute the function get_order_status("48213") → {"status": "shipped"} 3 messages + tool_call + {"role":"tool", …result} you send the whole history plus the tool result 4 "Your order 48213 has shipped." 5 now it answers, grounded in real data
Step 5 · The contract

A tool is a function plus a good docstring

The decorator writes the JSON Schema from your signature. The docstring is prompt engineering.

how you define a tool
from langchain_core.tools import tool   @tool def get_order_status(order_id: str) -> dict: """Look up the live status, item and ETA of an order.   Use whenever the user asks where their order is. Do NOT use for orders older than 90 days.   Args: order_id: The numeric order id, e.g. 48213 """ return db.query("…", order_id)   model.bind_tools([get_order_status]) # offer it to the model
The description is the whole game

The model picks a tool by reading your docstring. A vague one means the wrong tool, or none at all. Write it for a new colleague on their first day.

Say when not to use it

"Use only for orders placed in the last 90 days" prevents more bad calls than any amount of system-prompt scolding.

Keep the menu short

Accuracy drops as the tool list grows. Past roughly 15–20 tools, group them or retrieve the relevant few per request.

You have seen this before

Underneath it is the same JSON Schema as structured output. One machine, two uses: constrain the answer, or choose an action.

Step 6 · The agent loop

An agent is a while loop around a tool call

Not a simplification for beginners, genuinely the architecture. Then create_agent writes it for you.

1 · Model decides answer, or call a tool? 2 · Your code acts runs the function 3 · Observe append result to messages 4 · Repeat call the model again exit when it answers instead of calling a tool LLM + tools + a loop plus a hard cap on iterations
the agent loop, by hand
model_with_tools = model.bind_tools(TOOLS) messages = [HumanMessage(task)]   for step in range(MAX_STEPS): # the guardrail reply = model_with_tools.invoke(messages) messages.append(reply)   if not reply.tool_calls: # it answered → done return reply.content   for call in reply.tool_calls: # it asked → act messages.append(BY_NAME[call["name"]].invoke(call))
…and the version you actually ship
from langchain.agents import create_agent   agent = create_agent(model=model, tools=TOOLS, system_prompt="You are a support agent.")   agent.invoke({"messages": [..]}, config={"recursion_limit": 12})

Same loop: plus streaming, retries, memory, approval gates and tracing. Read the twelve lines until they are boring, then never write them again.

Step 6 · Watch it run

The loop, actually running

A real trace, captured from the notebook. Press → to advance one step of the loop at a time.

User "My order 48213 hasn't arrived. How many days until it's due, and what's your policy if it's late?"
Think I need the order's ETA and the late-delivery policy. Two different tools. I can ask for both at once.
Act ×2 get_order_status({"order_id": "48213"})
search_policies({"query": "late delivery policy"})
Observe {"status": "shipped", "eta": "2026-09-16"…}
[shipping_faq.md] Orders delayed beyond the promised window…
Think I have the ETA and the policy, but the user asked how many days. I cannot do date arithmetic myself. Loop again.
Act days_until({"date_iso": "2026-09-16"})
Observe {"days_from_today": 4}
Answer "Your order 48213, a table lamp, is due in 4 days on 2026-09-16. If it is delayed more than 5 business days past the promised window you can cancel for a full refund [shipping_faq.md]."
Think Act Observe Done?
Rounds through the loop
1 2 3 then it stopped

It stopped by itself. Not because you counted to three, but because round 3 produced text instead of a tool call. That is the only exit condition there is.

Step 6 · Judgement

Most agents should have been a workflow

Agents are the exciting answer. They are usually the wrong one.

Workflow you decide the steps
classify retrieve draft send
  • Predictable cost and latency, you can quote a number
  • Debuggable: a failing step is a failing function
  • Testable step by step, like any pipeline

Use when you can draw the flowchart. Which is most of the time.

Agent the model decides the steps
model chooses tool? tool?
  • Cost and latency vary per request, hard to promise an SLA
  • Failures are emergent: it took a path you never imagined
  • Needs real evals and tracing before you can trust it

Use when the steps genuinely depend on what earlier steps found.

The honest heuristic: if you can draw the flowchart, write the flowchart. Reach for an agent when you genuinely cannot know the next step until you have seen the last one.

Step 6 · Before it touches production

The five things that stop an agent hurting you

A loop with real tools and a company credit card deserves the same paranoia as any other privileged process.

1 Iteration cap

A hard MAX_STEPS, plus a token or rupee budget per task. When it trips, stop and surface it, never loop silently.

2 Read vs write split

Reads can run freely. Anything that writes, sends, pays or deletes goes behind explicit approval or a confirmation step.

3 Validate arguments

Tool arguments are model output. Treat them exactly like untrusted user input: validate, bound, and scope every one.

4 Return errors, don't raise

Hand a failed tool call back as text the model can read. It will often recover on the next turn. An uncaught exception kills the run.

5 Trace everything

Log every prompt, tool call and result with a run id. You cannot debug what you cannot replay, and you will need to replay.

And the one people forget

A retrieved document can contain instructions. If your agent reads untrusted content and holds write tools, indirect prompt injection is a real attack, not a thought experiment.

Three hours later

What you can now build

Each layer is the one below it plus a single idea. You wrote every one of them yourself.

1An LLM callmessages, system prompt, temperature, max_tokens
2A conversationhistory you keep and resend, by hand, then with a checkpointer
3A budget you can defendtokens in, tokens out, context window, rupees per thousand users
4A software componentschema-enforced JSON your code can parse without fear
5Answers grounded in your own datasplit, embed, retrieve, paste into the prompt, cite the source
6Something that can actthe model asks, your code executes, the result goes back
7An agentall of the above in a loop create_agent, with a cap and an approval gate

You have not learned a framework that will be obsolete in eight months. You have learned one interface that spans every model and the same objects carry straight into LangGraph, LangSmith and Deep Agents.

The roadmap from here

Where this goes next

Four tracks, in the order that compounds. Every one of them sits on the interface you learned this morning.

Track 12–3 weeks
LangSmith & evals
  • Evals: a 50-case set you score every change against. Start here.
  • Tracing every step, token and rupee
  • Prompt caching and cost control
  • Hybrid search and reranking
  • One env var away, you already wrote the code
Track 23–4 weeks
LangGraph & Deep Agents
  • LangGraph: custom control flow, branching, durable state
  • Deep Agents: planning, subagents, long-horizon memory
  • MCP: the standard way to expose tools
  • Context engineering & compaction
  • Both built on what you learned today
Track 3ongoing
Spec-Driven Development
  • Writing specs precise enough for a coding agent to execute
  • Repo conventions files agents read
  • Plan first, then build, then verify
  • Reviewing AI-written code properly
  • The highest-leverage skill of the next two years
Track 4when shipping
Production
  • Prompt injection & data-leak review
  • Rate limits, fallbacks, multi-provider
  • PII handling and regional routing
  • Model upgrades without regressions
  • Fine-tuning, last, and rarely

Safe to skip for now: transformer internals, training your own model, GPU infrastructure, and every "which framework" debate on the internet. You have picked one. Go deep before you go wide.

Concretely

The next 30 days, if you want this to stick

Knowledge you do not use within a week is knowledge you did not keep.

Week 1
Rebuild today from an empty file

No copying from the notebook. An LLM call, a RAG over your own PDFs, one tool, one loop. The struggle is the point, it is where it moves from watched to known.

Week 2
Ship one small thing to one real user

Anything: a CLI over your notes, a Slack bot for your team, a classifier for your inbox. Real users find failures no amount of local testing will.

Week 3
Write the eval set

Fifty inputs with expected outputs. A script that scores them. Now change the model and watch the number move. This is the week you become dangerous.

Week 4
Write it up in public

A post, a repo with a decent README, a short demo video. In this field a public artefact is worth more than a certificate, and it is how people find you.

One rule for all four weeks: when something breaks, print the exact prompt that was sent before you change anything. Almost every bug in this field is visible in that string, and almost nobody looks at it.

That's the workshop

You do not need to build LLMs.
You need to build with them.

An API call, a conversation you keep, a budget you can defend, a schema, some retrieved context, a tool, and a loop. That is the foundation, and it is enough to start shipping.

01 · first call02 · tokens & cost 03 · structured output04 · RAG 05 · tool calling06 · agent loop

Everything from today is in the repo: this deck, six runnable notebooks, the sample documents, and a one-page LangChain cheat sheet. Rebuild week one from an empty file, not from the notebook.

Questions, and then go and build something small today, while it is still fresh.

AI Fundamentals · Data Sense

Presenter controls

→ / SpaceNext step, then next slide
←Previous step or slide
↑ / ↓Skip a whole slide
N or SSpeaker notes panel
OOverview of all slides
TShow timer, then start / pause it
RReset the timer
FFullscreen
1 2 3 …Jump to slide number
?This help
Press ? for controls · N for speaker notes · F for fullscreen