A crash course in the concepts, patterns, and practical knowledge you need to build an AI-powered MVP.
Built on the Transformer architecture (2017).
Every AI tool you've used runs this pipeline:
Text → tokens → vectors
Each token weighs all others
Next token probabilities
Pick one token, append
Loop until done
No stored facts — only learned patterns
Context window = temporary memory only
Same input can give different outputs
It simulates language, not retrieves truth.
Plausible ≠ correct (hallucination)
Small prompt changes → big output shifts
You shape behavior through structure
You're programming behavior, not querying knowledge.
LLMs are stateless — memory must be built around them.
Think of it as a desk.
You can only have so many papers on it at once.
The model can only see what's on the desk.
Every architecture pattern we'll learn today — RAG, memory, tool use — exists to manage what goes on this desk. That's the whole game.
// A token is NOT a word. It can be: // - a whole word - part of a word // - punctuation - a space + word // "Tokenization is surprisingly tricky!" ["Token", "ization", " is", " surprising", "ly", " tricky", "!"] // 7 tokens // Common suffixes (-ing, -tion, -ly) = 1 token // Rare words get split into pieces: "ChatGPT" → ["Chat", "G", "PT"] // 3 tokens "🏠" → ["🏠"] // 1 token "$450,000" → ["$", "450", ",", "000"] // 4 tokens
100 API calls with Claude Sonnet costs ~$0.30. Your entire hackathon's API usage will probably cost less than lunch. Don't let cost anxiety slow you down.
Strip away every framework and abstraction.
This is all it is.
import anthropic # pip install anthropic client = anthropic.Anthropic() # uses ANTHROPIC_API_KEY env var response = client.messages.create( # send request → get response model='claude-sonnet-4-20250514', max_tokens=1024, messages=[ {'role': 'user', 'content': 'What is machine learning?'} ] ) print(response.content[0].text) # extract text from response
Five lines of real code. Everything else — LangChain, LlamaIndex, frameworks — is a wrapper around this.
Give the model distinct sections.
Each one constrains its output differently.
# Your code builds this template once # {vars} are injected at runtime — dates, user data, docs ROLE: You are a senior backend engineer who writes clean, production-ready Python. CONTEXT: Stack: FastAPI + SQLAlchemy, PostgreSQL 15. Today's date: {date} User timezone: {timezone} Order model: id, user_id, total, status, created_at CONSTRAINTS: Max 50 results, support pagination, sort by created_at DESC, return empty list if none, use typed Pydantic response models. FORMAT: Respond with only Python code. No explanation.
# This changes every turn — the actual request I need an endpoint that returns a user's most recent orders. Something like GET /users/{user_id}/orders
Sets expertise level and voice. "Senior backend engineer" produces different code than "helpful assistant."
This can be your stack, your data, your user — whatever your code injects at runtime.
One clear instruction. Ambiguity here is the #1 cause of bad outputs.
Prevents over-engineering and scope creep. The model will add features you didn't ask for without these.
Controls output shape. "Only code, no explanation" eliminates preamble you'd have to strip.
The left card shows how these sections map to the actual API call. Both are sent together on every request:
System message — the model's job description. The template stays the same, but your code injects variables at runtime — current date, user preferences, retrieved documents, etc. LLMs are stateless, so you re-send it on every call.
User message — the work ticket. This is the only part that changes per turn.
This split is a guideline. If context varies per request (e.g., different data), move it to the user message.
The model only knows what's in the context window.
It hasn't read your docs, your database, or your product.
How do you give it that knowledge?
This is where embeddings, RAG, and memory come in.
Turn text into numbers so "similar" things are nearby.
Like GPS coordinates, but for meaning.
"dog ran fast"
↔ "puppy sprinted quickly"
0.92
cosine similarity
"bake a chocolate cake"
↔ "recipe for brownies"
0.89
cosine similarity
"dog ran fast"
↔ "stock market crashed"
0.11
cosine similarity
Don't train the model on your data.
Just retrieve the relevant parts and put them in the prompt.
User asks a question
user input
Convert query to vector
model
Find similar chunks
deterministic
Inject into prompt
deterministic
LLM answers with context
LLM
RAG quality is a search problem, not an AI problem. Bad answers? Fix your retrieval first.
The bridge between "cool demo" and "reliable feature."
The product has a rating of about 4.5 stars. Most users liked it. Some complained about the weight. Price is $299.
{
"rating": 4.5,
"pros": ["battery life", "display"],
"cons": ["weight"],
"price": 299,
"recommendation": "buy"
}
json.loads()LLMs are stateless. Every API call starts fresh.
If you want a conversation, YOU send the history.
Send the full chat history every call. The list grows each turn.
Simple. Start here. Works until you hit context limits.
When history gets long, ask the AI to compress it.
Trades detail for token savings. Good for longer sessions.
Don't send everything — retrieve only the relevant past turns.
Same cosine math as RAG. Best for apps with long histories.
Extract facts from conversations. Store in a database. Query as needed.
Most complex. Best for production systems.
The model requests actions. Your code executes them.
The model never runs code directly.
"Weather in Dallas?"
Requests get_weather
Runs the function
Formats the response
The model requests. You execute. That's the safety boundary.
Best reasoning, most capable. Slower, costs more.
Fast responses, good enough for most tasks. Great for real-time UX.
Cheapest per token. Good for high-volume, simpler tasks.
Your summarizer doesn't need the same model as your reasoner. A well-prompted smaller model often beats a poorly-prompted frontier model. Mix and match.
This changes your architecture, UI, error handling,
and demo strategy.
The entire UX is the AI interaction. The AI is front and center.
Focus: prompt quality, conversation design, response speed
A traditional app enhanced with AI capabilities. AI works behind the scenes.
Focus: integration quality, graceful fallbacks, UX consistency
Decide which one you're building before writing code. It shapes every decision that follows.
One primary pattern per project.
Extend only when needed.
Pick one core pattern
RAG + Chat
Q&A over docs, knowledge bases
Chat + Memory
Assistants, tutors, support bots
Prompting + Structured Output
Copy, summaries, reports, code
+ Layer extensions as needed
Tool Use
Let the AI take actions
Multimodal
Analyze images / docs
Agents (advanced)
Multi-step automation
You don't need to understand everything — you need to understand enough to make good decisions and build something real.
LLMs predict tokens. The context window is your constraint. Prompting is your highest-ROI skill. RAG gives the model your data. Tools let it take actions. Test with 15 golden examples. Start simple. Ship it working.
Connect with your team, mentors, and the community.
promptengineersai.slack.com
Text is broken into small units (tokens) and converted into vectors the model can process.
Text → numbers. Everything after this is vector operations.
Each token computes a relevance score against every other token, assigns weights, and blends their information.
What matters? This is how context flows between tokens.
The model transforms token representations into next-token probabilities through stacked layers.
Transform meaning. "Reasoning" emerges from repeated transformations, not logic rules.
The model selects the next token from a probability distribution.
Choose next step. Same input can produce different outputs — behavior is controlled, not fixed.
The entire pipeline runs once per token. A 500-word response is ~700 iterations of this loop.
This is why longer responses cost more (more tokens = more compute) and why streaming works token-by-token.
The user asks a natural language question. This is the only human input in the pipeline.
This raw text gets passed to the embedding model in the next step.
The query is converted into a vector — same embedding process as your pre-stored docs.
Your docs were embedded the same way at ingest time. Now both are in the same vector space.
Compare the query vector against every stored doc vector using cosine similarity. Pure math — same query always returns the same results.
No LLM involved here. This is an Information Retrieval (IR) operation.
Take the top matching chunks and inject them into the prompt as context. This is literally string concatenation.
RAG is just: stuff relevant docs into the prompt. That's the whole trick.
The LLM receives the augmented prompt and generates an answer grounded in the retrieved context.
This is the only probabilistic step. Everything before it was deterministic math.
The model receives available tools + conversation history and predicts the next step. Tools can be functions, APIs — or even other agent loops (sub-agents) that run their own cycle internally.
At its core: next-token prediction over the tool menu + context. Advanced systems add evaluators, routers, and sub-agents — but this loop is always the foundation.
Extract the tool request from the response. Your code executes it — the model never runs code, it only generates a structured request.
The safety boundary: the model requests, you execute. Same pattern as single tool use.
Append both the assistant's tool request and the tool result to history. The model sees this on the next call — it has no live awareness. In advanced systems, evaluators (separate LLM calls) can grade the result before continuing.
Both messages required: the assistant's request + the tool's response. Evaluators and sub-agents plug in here as additional LLM calls or nested loops.
The entire agent is a while loop. If the response contains a tool_use block, keep going. If the model returns only text, it's done.
That's the entire agent. A while loop, tool extraction, execution, and history updates. Everything else is a wrapper around this.