README.md
Setup and the map of the library. 164 lines, standard-library Python.
# Agentic AI, End to End
The code for the [Agentic AI course](https://systemcraft.in/agentic-ai/) on SystemCraft.
A small, readable agent toolkit built from scratch — no LangChain, no CrewAI, no
framework of any kind — so that when you later pick one up, you already know what
it is doing for you.
## Get it
Download the folder as a zip:
**[systemcraft.in/downloads/agentic-course.zip](https://systemcraft.in/downloads/agentic-course.zip)**
```bash
unzip agentic-course.zip
cd agentic-course
```
Or read any file in the browser at
[systemcraft.in/agentic-ai/code/](https://systemcraft.in/agentic-ai/code/),
which lists every module and test alongside the lesson that builds it.
The site repo this folder lives in is private, so `git clone` and `npx degit`
against it will not work. The zip is built from this directory on every deploy,
so it is never stale.
## Run it
No `pip install`. No virtualenv. No API key.
```bash
python3 demo.py # full stack, 6 scenarios
python3 -m unittest discover -s tests -t . # 132 tests
```
Requires Python 3.10+. Standard library only.
## Why it runs offline
Everything talks to a model through one method, `Model.complete`. That single seam
is the whole trick: `FakeModel` is scripted and deterministic, so an agent loop, a
trace, and an eval suite behave identically whether a real provider is on the
other end or not.
```python
from agentic import Agent, FakeModel, Registry, tool, tool_call
@tool(description="Look up an order by id.", order_id="The order id.")
def get_order(order_id: str) -> dict:
return {"id": order_id, "status": "delivered"}
model = FakeModel([
tool_call("get_order", {"order_id": "4471"}),
"Order 4471 was delivered.",
])
run = Agent(model, Registry([get_order])).run("Where is order 4471?")
run.output # "Order 4471 was delivered."
run.trajectory() # ["get_order"] - tools that actually RAN
run.stop # Stop.ANSWERED
```
Point it at a real model by implementing `complete`. That is the only change.
## Modules
| File | What it is | Read it for |
|---|---|---|
| `model.py` | The model boundary, `FakeModel`, a thin HTTP adapter | Why the seam makes agents testable |
| `tools.py` | Schemas, validation, authorization, dispatch | The security boundary of an agent |
| `loop.py` | The agent loop, budgets, named stop reasons | What every framework wraps |
| `memory.py` | History windows, summarization, a fact store | Why memory poisoning is the real risk |
| `trace.py` | Nested spans, token and cost accounting, redaction | Why a trace is the bug report |
| `evals.py` | Golden cases, trajectory scoring, a judge with kappa | The skill that separates shipped from demoed |
| `guard.py` | Fencing, policy, egress and confirmation gates | Containment when prevention is impossible |
| `retrieval.py` | Cosine, a vector store, BM25, RRF, rerank | Why hybrid beats dense-only |
Each file is short enough to read in one sitting. That is deliberate.
## Three ideas the code is built around
**A loop with no budget is not an agent.** It is a `while` loop with a credit card
attached. `Budget` caps steps, tokens, cost, and repeated identical calls, and
every run ends with a *named* `Stop` reason. There is no unnamed terminal state.
**Requested is not executed.** `run.trajectory()` lists tools that actually ran;
`run.requested_tools()` lists what the model asked for. Conflating them makes a
working guardrail look like a breach — a blocked injection would fail a
`never_used("refund")` assertion even though the defense held. The two together
distinguish *the attack never landed* from *the attack never started*.
**Prompt injection is contained, not prevented.** Instructions and data share one
channel, so no phrasing makes a document's text non-instruction. `Policy`
therefore removes capability: `for_untrusted_input()` drops every tool from a
context that has read foreign text. `demo.py` scenario 3 shows a fully
compromised model that still cannot issue the refund.
## Tests as documentation
The test names are the curriculum:
```
test_step_budget_stops_a_runaway_agent
test_repeated_identical_call_is_detected
test_internal_exception_does_not_leak_details_to_the_model
test_unknown_tool_does_not_reveal_hidden_tools
test_missing_confirm_handler_crashes_rather_than_degrading
test_permission_filter_runs_before_ranking
test_rrf_combines_by_rank_not_score
test_always_pass_judge_has_zero_kappa_despite_high_agreement
test_injected_document_cannot_reach_a_mutating_tool
test_protected_keys_cannot_be_written_by_an_agent
```
Each one encodes a failure mode that costs real money in production. Two of them
exist because writing the tests found genuine design bugs in this library — a
misconfiguration that degraded into a normal-looking stop reason, and the
requested-versus-executed conflation above.
## Using a real model
```python
from agentic.model import Completion, HTTPModel, Message
class MyProvider(HTTPModel):
def _parse(self, payload) -> Completion:
choice = payload["choices"][0]
return Completion(
text=choice["message"].get("content") or "",
finish_reason=choice.get("finish_reason", "stop"),
input_tokens=payload["usage"]["prompt_tokens"],
output_tokens=payload["usage"]["completion_tokens"],
model=payload.get("model", self.model),
)
```
Field names and endpoints differ per provider and change over time, so the course
ships no provider defaults on purpose — look them up in your provider's current
docs rather than trusting a constant baked in here. Add tool-call parsing to
`_parse` when your provider returns them.
## Honest limitations
- `HashingEmbedder` is a bag-of-words hash, **not** a semantic model. It cannot
tell that "cheap" and "inexpensive" are related, because it has learned
nothing. It exists so the retrieval mechanics — dimensionality, normalization,
cosine, indexing, fusion, permission filtering — run offline end to end. Swap in
a real embedding model for anything real, and note that doing so means
re-indexing the whole corpus, never a config flip.
- `VectorStore` is exact brute-force search, linear in corpus size. Real systems
use approximate indexes (HNSW, IVF-PQ) and treat recall as a tunable SLO. Brute
force is the correctness baseline you measure those against.
- `keyword_overlap_reranker` has the *shape* of a cross-encoder without being one.
- `guard.scan` is a pattern matcher. It will always be incomplete — an attacker
needs one phrasing you did not think of, and paraphrase is free. Use it for
logging and triage, never as the thing standing between an attacker and a tool.
- No async. The concurrency lesson covers it; the library stays synchronous so the
control flow is readable.
## License
MIT. Use it, fork it, teach from it.