AIS
Agent Foundations Code Library · v0.1.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.

Stage 0 of the agent-engineering ladder, complete. A new episode airs daily; its code lands in the library at no extra cost.

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

24 patterns today — one for every episode aired so far, from “what is an agent” through prompts, structured output, tool calling, and context engineering. Season 1 is 60 episodes; the library keeps pace.

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.

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.

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.

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.

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.

06

Layered instruction stack

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

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

Where it sits

The free starter pack

  • · Four of these patterns, unchanged
  • · Enough to see how AIS builds
  • · Stops at the on-ramp

Agent Foundations Code Library

$19 · one-time
  • · All 24 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

Buy — $19 →
  • Every pattern from the series — 24 today, 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.