A small typed Python library for tool-using LLM agents: a validated tool registry, an agent loop with cost and time limits, a response cache, an evaluation harness and prompt-injection hygiene. All of it runs and is tested offline with a scripted fake model, so it needs no API keys and no network.
It shows AI/LLM engineering: agents and tool use, cost-aware tooling, and evaluation.
Needs Python 3.12 or newer.
python3 -m venv .venv && . .venv/bin/activate
pip install -e ".[dev]"
pytest && python -m examples.demoCI also runs ruff check ., ruff format --check . and mypy (strict). The demo prints a readable transcript, cost and an eval report.
- Tool use is validated at the boundary. Arguments are checked against each tool's JSON Schema before the handler runs; failures come back to the model as an error that names the bad field. Results are typed (
ToolResult). A tool runs only if an approval callback says yes, unless it is declaredrequires_approval=False: the library cannot know which handlers have side effects, so the safe choice is the default. A handler's exception text stays with the caller (ToolResult.detail); the model sees only the exception's type. - The loop is bounded. It stops with an explicit reason (
final,incompletewhen the provider cut a reply off or withheld it,max_turns,budget,timeout,model_error), refuses a call whose worst-case cost would pass the budget, clamps each call's timeout to the time left, and retries only transient errors with capped exponential backoff. - Cost is tracked and capped. Per-call and per-run totals use
Decimal, and the price table is user-editable (PriceTableor a JSON file). A cached response is billed at zero, identical requests made at the same moment from several threads reach the backend once, and a test shows a repeated eval run costs zero on its second pass. - Evals report uncertainty. Graders are exact, contains, JSON-schema and custom functions. The report gives pass rate, a Wilson 95% interval and cost, and
comparelists regressions and improvements between two runs. - Injection hygiene is tested. Tool output is wrapped, labelled as untrusted data and cannot close its own wrapper. Six injection payloads are checked, along with a scripted "fooled" model that tries a side effect and is stopped by the approval gate.
Layout: src/llm_tooling_lab/ holds one small module per job (tools, agent, cost, cache, retry, evals, safety, fake, types, plus adapters/). tests/ mirrors it, and examples/demo.py is the offline walkthrough.
An independent AI review of the source (2026-11-26) found six faults that the first 70 tests did not. Each got a test that failed on the old code, then a fix:
| Fault | Fix |
|---|---|
| A tool ran without approval unless it had been flagged | Approval is the default; read-only tools opt out |
| Exception text, which can hold secrets, was sent to the model | Only the type is sent; the text is kept in ToolResult.detail |
| A cut-off reply was reported as a final answer, and its tool calls would run | New incomplete stop reason, read from each provider's finish reason; no tool runs |
| A handler or approver could change the arguments recorded in the conversation | Each gets its own copy |
A result such as {1: ..., "a": ...} crashed the run; NaN went out as invalid JSON |
Encoded strictly inside the guarded call |
| Two threads asking the same thing both called, and paid for, the model | One call per key; others wait, within their timeout |
A second review of the fixes found more: a caller waiting for another's request could then spend its whole timeout again; tool calls ran when the provider gave no finish reason; and the concurrency test could pass without the lock. The wait now comes out of the timeout, tool calls need a stated finished reason, and the test waits until the second caller is known to be blocked.
With these, 100 tests pass (three runs on a second Linux machine), and deliberate breaks of the new code were each caught: 13 after the first round and 5 more after the second.
I changed the code to be wrong, confirmed the intended test failed, and restored it. Each run was the full suite of 70 tests.
| Break | Test that caught it |
|---|---|
Budget guard off by one (> became >=) |
tests/test_cost.py::test_budget_allows_spend_exactly_at_the_limit (only this one failed) |
Cache key ignores temperature |
tests/test_cache.py::test_key_changes_with_temperature and test_different_temperature_is_a_miss_not_a_stale_hit |
| Schema validation skipped | tests/test_tools.py::test_invalid_arguments_rejected_before_handler_runs, plus two more |
| Retry backoff cap removed | tests/test_retry.py::test_backoff_delay_is_capped (delay reached 1024.0 instead of 8.0) |
Wrapper stops neutralising </tool_result> |
three tests in tests/test_injection.py, including the two payloads that try to close the wrapper |
On 2026-11-25 the repository was cloned fresh onto a second machine (Linux, CPython 3.12.12 from uv), where ruff check, ruff format --check, mypy (strict) and pytest (70 tests) all passed and the offline demo ran. Three of the breaks above (budget guard, backoff cap, tool-result wrapper) were repeated there and each failed the same tests.
- The injection tests check the harness, not a model. The
FakeModelis scripted, so these tests show how the loop wraps and handles tool output and gates side effects. They say nothing about how a live model resists injection, and wrapping does not make a model safe on its own. - The live adapters are untested against live services.
adapters/anthropic.py(Messages API) andadapters/openai_compat.py(chat-completions format) use plainhttpxand read keys fromANTHROPIC_API_KEY/OPENAI_API_KEYonly. They were written from public API documentation and checked offline against hand-written fixtures through a mock transport. They have never been called against a live endpoint, and nothing in CI or the tests contacts one. - Prices are examples.
EXAMPLE_PRICESholds made-up numbers so the demo has something to compute. They are not any provider's pricing; set your own. - Token counts for the budget guard are estimates. Before a call the loop projects input as characters divided by four plus the full
max_tokensoutput, which is conservative and not a tokenizer. A cache hit is still projected at full cost before the budget check. - Timeouts are cooperative. The loop passes a timeout to the client and checks the run deadline between turns; it cannot interrupt a client that ignores its timeout, and retry sleeps are not counted against the run deadline while they happen.
- The cache is in memory and per process, never evicts, and keys on the request, not on any notion of "same meaning".
- Evals grade the final text only. The demo and tests are small constructed examples (3 to 4 cases), so their intervals are wide on purpose.
- Measured once (n=1), on an AMD Ryzen 5 PRO 5650U, Python 3.12: the first suite of 70 tests ran in about 0.5 to 1 second.
httpx and jsonschema at runtime. pytest, ruff, mypy and types-jsonschema for development. All are normal public packages and are not vendored.
MIT. See LICENSE.