AIS
Agent Foundations Code Library · v0.2.0

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.

Watch the series on YouTube

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.

Agent Foundations Code Library, bound as a cloth book with a gold-foil cover

Watch free. Run instantly. Own forever.

01

Watch

A new Agent Foundations episode airs daily on the AIS YouTube channel — one beginner concept per day, free. The videos teach the why.

02

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.

03

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
01

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.

Watch the episode
02

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.

Watch the episode
03

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.

Watch the episode
04

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.

Watch the episode
05

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.

Watch the episode
06

Layered instruction stack

A system/developer/user instruction stack that resolves same-topic conflicts by fixed precedence and renders deterministically.

Watch the episode
07

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.

Watch the episode
08

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.

Watch the episode
09

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.

Watch the episode
10

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.

Watch the episode
11

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.

Watch the episode
12

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.

Watch the episode
13

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.

Watch the episode
14

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.

Watch the episode
15

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.

Watch the episode
16

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.

Watch the episode
17

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.

Watch the episode
18

Tool definition linter

Tool definitions (name, description, typed parameters) render into one deterministic text block, checked by a linter before any model sees it.

Watch the episode
19

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.

Watch the episode
20

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.

Watch the episode
21

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.

Watch the episode
22

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.

Watch the episode
23

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.

Watch the episode
24

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.

Watch the episode
25

History Compactor

Drop dead ends, summarize finished work, keep recent turns verbatim, and pin every rule so compaction never quietly breaks one.

Watch the episode
26

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.

Watch the episode
27

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.

Watch the episode
28

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.

Watch the episode
29

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.

Watch the episode
30

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.

Watch the episode
31

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.

Watch the episode
32

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.

Watch the episode
33

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.

Watch the episode
34

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.

Watch the episode
35

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.

Watch the episode
36

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.

Watch the episode
37

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.

Watch the episode
38

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.

Watch the episode
39

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.

Watch the episode
40

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.

Watch the episode
41

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.

Watch the episode
42

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.

Watch the episode
43

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.

Watch the episode
44

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.

Watch the episode
45

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.

Watch the episode
46

Typed Stop Conditions

Engineer six explicit reasons for an agent to stop, verify success before declaring it, and record why every run ended.

Watch the episode
47

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.

Watch the episode
48

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.

Watch the episode

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 included
  • · 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

Buy — $19 →
  • ✓ 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
  • ✓ Updates included 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.