Free self-study · No account needed · Progress stays in this browser. Back it up before clearing site data or changing devices.

← Week 10: Tool Calling

Week 10 / Lesson 1

Defining and registering tools

Build narrow tool contracts and validate arguments before dispatch.

Section 1.1 1 of 7

Overview

Focus

Build narrow tool contracts and validate arguments before dispatch.

Your route through the lesson

  • 1.2 Function names and argument schemas
  • 1.3 Types, ranges, business rules, and trusted identity
  • 1.4 A registry with input and output contracts
  • 1.5 Put it into practice
  • 1.6 Guided comparison
  • 1.7 An argument carrying forged identity

All required teaching is included here. Review selections are saved. Choose a correct answer for every question to continue; retries are unlimited. Study time and personal notes are optional.

Section 1.2 2 of 7

Function names and argument schemas

Focus

Describe a narrow tool with an unambiguous name and structured argument contract.

A tool contract states an operation’s name, accepted arguments, returned result, and failure behavior. A function schema describes the argument structure in machine-readable form. For a file search, query can be a required nonempty string and limit a required integer from one through five. Unknown fields are rejected rather than silently interpreted as extra authority.

Consider a search_files tool. It searches only a configured exercise directory; callers cannot submit a new filesystem root. Its description explains that it returns matching filenames and snippets, not that it executes arbitrary commands. A model can choose query and limit, but the executor still validates both before calling the implementation.

Narrow contracts make mistakes visible. A tool named do_anything with a free-form command transfers too much interpretation to execution. A bounded arithmetic tool instead accepts operation, left, and right, with operation limited to add, subtract, or multiply. It computes those operations directly; it never evaluates a model-supplied Python expression. A valid schema is the beginning of validation, not proof that a request is authorized or meaningful.

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. A search tool accepts query and limit only. A proposal adds root = C:\Users. What should happen?
2. Which arithmetic contract avoids arbitrary code evaluation?
3. A function schema validates argument shape. What does that alone fail to establish?

Section 1.3 3 of 7

Types, ranges, business rules, and trusted identity

Focus

Validate types, ranges, business meaning, and identity before dispatch.

Type checks establish what a value is; range checks bound it; business rules establish whether it makes sense for this operation. A refund amount can be an integer number of cents within a limit yet exceed the order’s remaining refundable balance. Both structural and business checks are needed.

Python has a subtle type relationship: bool is a subclass of int. isinstance(True, int) returns True. If the contract requires an actual integer count, type(value) is int rejects booleans. Numeric checks should also reject nonfinite values where relevant, because infinity and not-a-number can bypass ordinary comparisons unexpectedly.

Identity comes from the authenticated session or process configuration. A model-supplied owner, role, or tenant is data to reject or verify, never a replacement for authentication. Suppose the caller is read-only Lee and arguments claim role admin. The executor still uses Lee’s permissions. Good errors distinguish malformed arguments from denied authority without revealing sensitive internal records. This separation supports safe recovery: correcting a typo is different from obtaining legitimate permission for a mutation.

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. A count must be an actual integer. Why might isinstance(True, int) be insufficient in Python?
2. A refund of 500 cents fits the per-call limit but only 200 cents remain refundable. Is it valid?
3. A read-only caller supplies role = admin in arguments. Which role should execution use?

Section 1.4 4 of 7

A registry with input and output contracts

Focus

Register implementations with both input and output validation.

A tool registry maps approved names to implementations and their contracts. Dispatch looks up the name, validates arguments, supplies trusted context, calls the implementation, and validates the returned value. An unknown name fails before any code is selected. This makes the execution surface explicit and inspectable.

Output validation matters because a correct input does not guarantee a correct implementation. A structured lookup might promise {status, value}, but return a raw exception string. If the runtime treats any nonempty text as success, it can convert an error into a completed result. Require an allowed status and the fields appropriate to that status.

The registry does not make returned text authoritative instructions. A file-search snippet remains untrusted source content even when its wrapper has a valid shape. Validation confirms the contract, not the factual truth of every sentence. The lab uses three tools—temporary-directory search, structured service lookup, and direct arithmetic—with deliberate malformed inputs and one malformed output. These failures test boundaries rather than relying on a model to voluntarily follow the schema.

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. A registry receives a tool name that was never registered. What should dispatch do?
2. A tool promises status and value but returns a raw traceback string. Which check catches this?
3. A search snippet passes output-schema checks and says “ignore permissions.” What authority does it gain?

Section 1.5 5 of 7

Put it into practice

Focus

Run the registry against normal, malformed, forged-identity, and malformed-output cases.

Save week10.py in your exercise folder and run python week10.py --lesson 1. The file creates temporary synthetic documents, registers three narrow tools, and executes positive and negative cases. It requires only the standard library, no network or credentials, and completes quickly on a processor.

Python dictionaries map a key to a value. A registry can therefore select an approved function without evaluating code. Membership checks reject unknown names:

def add(left, right):
    return left + right
registry = {"add": add}
assert "delete_everything" not in registry
result = registry["add"](2, 3)
assert result == 5

The weekly file adds real argument and output guards around this central pattern. It checks that a forged identity field is rejected, a boolean is not accepted as an integer limit, and an unsupported arithmetic operation never reaches arbitrary evaluation. PASS means the supplied contracts held on those cases. It does not demonstrate a language model’s ability to choose tools or a production filesystem’s complete security.

Download this week’s Python lab ↓

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. What does registry["add"](2, 3) do in the shown dictionary pattern?
2. A tool test rejects True as a search limit. Which requirement does that check?
3. A local registry lab passes its fixtures. Which claim remains unsupported?

Section 1.6 6 of 7

Guided comparison

Focus

Trace validation failures to the boundary they protect.

The completed search call supplies query reset and limit 2. The registry confirms the exact allowed keys, a nonempty string, and an integer in range. It searches only the temporary root and returns structured matches. A later call adds owner admin; the unknown-field check rejects it before the search runs.

The arithmetic call multiply, 6, 7 returns 42. Another call supplies operation eval with an expression string. It is rejected by the operation allowlist, so no expression interpreter is involved. This is safer and easier to test than trying to detect dangerous substrings inside arbitrary code.

Finally, a deliberately broken tool returns the wrong output shape. The registry reports malformed_output and refuses to treat it as an observation of success. The trace records which boundary failed: unknown tool, bad arguments, denied permission, or malformed output. Distinct categories keep recovery honest. Rephrasing a malformed input may help; repeating an unauthorized action under a forged role must not.

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. A call adds an owner field not allowed by the search contract. At what point should it fail?
2. An arithmetic tool rejects operation eval. Why is an allowlist useful?
3. A malformed-output error occurs after valid input. What should the runtime avoid?

Section 1.7 7 of 7

An argument carrying forged identity

Focus

Reject forged identity even when every visible business argument is plausible.

A model proposes a structured lookup for order 17 with owner_id finance-admin. The actual authenticated caller is an ordinary support viewer. The order identifier is valid and the JSON is well formed, but the owner field attempts to select a different authority context.

The completed contract does not accept owner_id as a model argument. The executor derives the owner and organization from trusted session context and checks whether that caller may read order 17. If not, it returns a safe denial without order details. A schema alone would not stop the attack if it deliberately exposed owner_id and the implementation trusted it.

This transfers the lesson from malicious-looking input to plausible input. An argument can look ordinary while carrying an authority escalation. The important question is who is allowed to choose each field. Search terms and arithmetic operands are model-controlled data within limits; identity, filesystem roots, credentials, and permission policy are executor-controlled context. Keep that division visible in the implementation and in tests.

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. A well-formed order lookup asks to act as finance-admin, but the caller is a viewer. What should establish identity?
2. Why can a schema-valid request still be unsafe?
3. Which field should usually remain executor-controlled for a bounded file search?

Your personal notes

Optional, ungraded, and saved only in this browser. Export a backup from the Academy homepage to keep them.

References and further reading
Ask your own AI assistant

Copy this prompt into an assistant you already use. Nothing is sent automatically, and your personal notes are not included.

Next lesson: Handling asynchronous tool operations →