From your first prompt to your first agent — with the code.
The code behind the daily Agent Foundations video series: every beginner pattern — prompts that don’t wobble, JSON you can trust, tools the model asks for and your code runs, context you decide — implemented, commented for adaptation, and tested. Not a framework. Small, readable files you copy into your project and own.
Stage 0 of the agent-engineering ladder. A new episode airs daily; its code lands in the library in the next release, at no extra cost.
Watch free. Run instantly. Own forever.
Watch
A new Agent Foundations episode airs daily on the AIS YouTube channel — one beginner concept per day, free. The videos teach the why.
Run
Unzip the library and run any pattern instantly: pure Python 3.10+, zero dependencies, no API key. A deterministic mock model is included; every example ships with its tests.
Own
Plug your real LLM client into one file, copy the patterns into your project, and keep them forever. As episodes air, their code lands in your library at no extra cost.
What’s in the library
48 patterns today — episodes 1–48, from “what is an agent” through prompts, tool calling, context engineering, RAG, memory, planning, and a working tool-use loop. Season 1 is 60 episodes; new episodes land in the next release.
Every example runs out of the box and ships with its own checks. We run every test before every release — the same discipline the series teaches.
# no install, no dependencies, no API key cd ep17-tool-calling-protocol python tool_protocol.py # watch the pattern run python test_tool_protocol.py # prove it works on your machine # then plug YOUR model into one file (core/model.py) # and copy the pattern into your project
Loop vs. single call
Contrasts a blind single model call with a minimal observe-decide-act-check-stop agent loop that has an explicit stop condition and an iteration cap.
Capability probe suite
Runs four narrow scripted probes (format-following, valid JSON, admitting unknown, exact tool-call syntax) and rolls them into a go/no-go capability report before trusting a model in a loop.
Grounded citations
Forces every claim in an answer to cite a source snippet id and verifies the citation actually contains the claim's key terms, accepting an honest 'not in the sources' as a valid answer.
Token budget guard
A chars/word-blended token estimator, a cost calculator from caller-supplied per-million-token prices, and a TokenBudget guard that refuses a call before it happens if it would break a spend cap.
Context window guard
Measures an assembled prompt against a model's real token budget and either fits it, trims/drops sections on purpose, or refuses loudly.
Layered instruction stack
A system/developer/user instruction stack that resolves same-topic conflicts by fixed precedence and renders deterministically.
Task spec wobble linter
A TaskSpec (goal, inputs, done-when, must/never) plus a linter that flags vague words, missing done-when criteria, and unmeasurable goals before a model call is spent.
Checkable negative constraints
Pairs a 'never do X' prompt instruction with a verifier function (no emails, no phone numbers, max length, banned phrases, numbers unchanged from input) run against the actual reply.
Relevance-ranked few-shot selection
Builds a scored example bank and selects the k most relevant examples for the current input by plain token overlap, formatted consistently and capped by total character budget.
Pre-schema output format control
Defines labeled-lines (KEY: value) and delimited-block output formats, generates the matching prompt instruction, and parses replies back into dicts with named errors.
STUCK block detection and routing
Gives the model an explicit STUCK-block escape hatch (reason, missing info, suggestion) and routes it to one of three handlers by reason type, instead of letting the model guess.
Robust JSON extraction without a repair call
Extracts JSON from messy replies (code fences, leading prose, embedded in a sentence) by locating balanced braces with quote-awareness, then validates required keys — no second model call needed.
Schema-first prompt and validator
Define required keys, types, enums, ranges, and max lengths once, and generate both the prompt's shape clause and the reply validator from that single Schema so they can never drift apart.
Destination-specific output sanitizers
Five narrow sanitizers (filename, shell-ish argument, enum allowlist, free text, URL scheme) that treat model output as untrusted input, checked by where it's headed rather than by one generic 'is this safe' guess.
JSON repair ladder with bounded re-ask
A deterministic, logged repair ladder (strip fences, drop trailing commas, normalize single quotes, close truncated brackets) applied cumulatively before ever spending a model call, then exactly one re-ask quoting the parse error if repair fails outright.
Reusable templated call_llm capstone
One call_llm(model, template, variables, required_keys, max_attempts) that renders named placeholders, refuses missing variables before touching the model, validates JSON against required keys, retries within a bound, and returns a CallResult with full attempt history, estimated tokens, and outcome.
Tool-calling loop
The model replies TOOL_CALL or FINAL; code runs the tool, feeds the result back, and loops until FINAL or a step cap.
Tool definition linter
Tool definitions (name, description, typed parameters) render into one deterministic text block, checked by a linter before any model sees it.
Argument validation gate
Every tool call is checked for required args, types, ranges, and enums before execution, with only numeric-string-to-int coercion allowed.
Tool selection policy
Detects overlapping tool descriptions, requires a one-line reason with every tool choice, and rejects a reason that claims a capability the chosen tool doesn't have.
Trim and store tool results
Trim large tool outputs by their shape (log/table/JSON) and always attach a provenance line, while keeping the untrimmed original retrievable by id.
Error envelopes and routing policy
Every tool call returns an {ok, result|error{kind, retryable, hint}} envelope instead of raising, and a policy table routes each error kind to retry-once, ask-user, try-another-tool, or abort.
Capability scopes and approval tokens
Tools declare required capability scopes (read, write, network, spend); sessions get an explicit grant, and dangerous scopes additionally need a single-use approval token per call, with every attempt audited.
Pin, rank, and pack context
Assemble an LLM's context as a decision: pinned items are always included, the rest are ranked by task relevance (token overlap) and greedily packed to a token budget, with an accurate report of what was left out and why.
History Compactor
Drop dead ends, summarize finished work, keep recent turns verbatim, and pin every rule so compaction never quietly breaks one.
Context Pollution Linter
Print and lint the assembled context: evict stale tool results and duplicates, catch contradicting rules, and trace odd answers back to the block that caused them.
File Excerpt Packer
Give the model labeled, budgeted excerpts picked by relevance to the question, plus a file listing, instead of pasting whole files or the whole repo.
Smallest Honest RAG
Look it up, then answer from evidence: blended keyword and embedding search, cited answers, and an honest 'not in the docs' when nothing matches.
Chunking Strategy Lab
Chunk one document three ways, run the same questions against each, and see side by side why chunking on structure beats raw character counts.
Cited Answer Validator
Every claim maps to a chunk and every chunk to a dated source: filter by version and age, then reject uncited or unsupported answers in code.
Prompt vs Context Triage
Diagnose a bad answer before you fix it: wrong shape is a prompt bug, missing facts are a context bug, and the model is blamed only after both check out.
One-Pass Tool Assistant
The tier capstone: question, validated tool choice, gated execution and a cited, schema-checked answer. One pass with no loop, and every boundary checked.
Typed Agent State
The transcript is what was said and state is what is true now. A typed state object, updated in code after every action, is what makes an agent loop possible.
Layered Agent Memory
Working, episodic and long-term memory as plain files plus retrieval: read at startup, write on purpose, and load only the memories the task needs.
Memory Hygiene Audit
One wrong saved fact poisons every future run. Audit memory for provenance, fact-versus-guess labels, retention and secrets, then fix it.
Model Bench and Escalation
Pick models by measuring them on your own golden tasks: cheap models for classify and extract, strong ones for judgment, with escalation, a fallback, and re-benchmarks to catch drift.
LLM vs Code Split
A task-decomposition worksheet that routes rules to code, formats to schemas, checks to tests, and only judgment to the model, with the cost difference shown in numbers.
Agent Success Charter
Write what the agent is for and how you would know it succeeded before any code: a self-validating charter that drives a bounded loop to a checkable finish line.
Narrow Agent Roles
Four role-definition blocks with scope, a short tool list, and a checkable output rule, plus a linter that catches do-everything bots and reviewers that can also write.
Agent Sandbox Setup
Scaffold a scratch environment for an agent: temp workspace, fixture files, fake APIs, a journal for undoing every write, and a teardown that leaves nothing behind.
Senses and Hands Catalog
Declare exactly what an agent can observe and do, with typed parameters, approval gates, an audit hook, and a claims check that catches actions the agent only says it took.
Agent Decision Policy
A may / must / must-not rulebook above the model: allowed tools, verify-after-write checkpoints, defined ask-for-help triggers, and hard stops, written into the prompt and enforced in code.
Plan Tracker
Break a goal into one-call steps, order them by dependency into parallel waves, track status in state, and replan without losing finished work.
Autonomy Level Dial
Give each action its own autonomy level, promote it one step at a time on evidence from clean runs, and demote it the moment something surprises you.
Permission Manifest
A JSON permission manifest per tool: read, write, execute and destructive grants, the strictest approval for money and outbound email, and scheduled reviews.
Typed Stop Conditions
Engineer six explicit reasons for an agent to stop, verify success before declaring it, and record why every run ended.
Agent Harness Map
Name the harness parts around the model (runner, tools, state, budgets, traces, guardrails), tick off the library file you built for each, and decode framework claims.
Minimal Tool-Use Loop
The capstone loop: the model decides, a gated tool runs, results update typed state, and a stop-checker rules every turn under a hard iteration cap.
Where it sits
The free starter pack
- · Four beginner patterns on the same topics
- · Enough to see how AIS builds
- · Stops at the on-ramp
Agent Foundations Code Library
$19 · one-time- · All 48 patterns from the series, tested
- · Runs offline — no API key, no dependencies
- · Grows with the daily series; updates free
- · Model-agnostic: works with any LLM
Tutorials & notebooks
- · Happy-path demos with no tests
- · Tied to one vendor’s SDK
- · Nothing you can paste into production
Get the library
$19 one-time · no subscription · covers your whole team
- ✓ 48 patterns from the series (episodes 1–48), implemented + tested
- ✓ Pure Python 3.10+ · zero dependencies · no API key
- ✓ Mock model included — swap in your real client in one file
- ✓ Free updates as new episodes air — buy once
- ✓ Email support at [email protected]
The honest deal: buy once and every future episode’s code is yours at no extra cost. Digital downloads are final sale — run the free four-pattern pack first; what you see there is exactly what the full library is made of.