smartyfy.mrindigi.com

Python Master Course V2 — 174. Tool Calling and Bounded Agent Workflows

Lesson 174: Tool Calling and Bounded Agent Workflows

A tool-enabled assistant proposes operations, but the application decides whether those operations may run. That separation is the central idea of this lesson. You will build a deterministic local workflow with two harmless tools: searching an included handbook and adding bounded integers. All proposals are explicitly simulated, model-free fixtures. The workflow validates names and arguments, applies a trusted permission set, and stops after a fixed budget without executing shell commands or contacting external systems.

Learning objectives

  • Represent proposed tool calls as validated structured requests
  • Apply allowlists, argument checks and step budgets
  • Distinguish planning suggestions from authorized execution

Prerequisites and setup

115: fakes and dependency injection; 173: structured output contracts

Use Python 3.11 or newer in a local project folder. This lesson uses only the standard library, works on a CPU, and needs no account, API key, network service, or downloaded model. Save the worked Python example as lesson174.py. Run the example before extending it; keep the original assertions as regression checks.

python lesson174.py

Separate proposal, policy, and execution

A proposed tool call is data describing a desired operation. It is not a function invocation and does not carry authority. The application must first identify the tool in a fixed registry, validate its arguments, and check permission from trusted application state. Only then may it invoke the corresponding function. Never evaluate a proposed tool name as Python code or import a module whose name came from model output.

The distinction remains important even for read-only tools. A search function might reveal confidential records or send a query to a third party. In this lesson the corpus is public fictional text and processing is local. A real application additionally needs identity, source access checks, destination restrictions, and action-specific confirmation where appropriate.

Bound the workflow at several layers

A step budget prevents indefinite tool loops, but it does not limit the time or memory consumed by one expensive call. Add argument limits, per-call timeouts for external dependencies, total deadlines, and output-size caps as the application grows. Count rejected proposals toward the budget so an invalid-call loop cannot run indefinitely. Keep retry limits separate and visible.

The workflow below accepts at most three proposals. Search queries have a length limit; arithmetic accepts two ordinary integers with limited magnitude. Python considers bool a subclass of int, so exact type checks intentionally reject True as a numeric argument. These restrictions are simple examples of a resource and behavior contract, not an all-purpose sandbox.

Preserve an audit trail without amplifying untrusted text

Record the tool name, decision category, and safe result needed to explain the workflow. Avoid copying raw proposed arguments into unrestricted logs, especially when they may contain personal data or injected instructions. Distinguish denied from invalid: denied means a recognized action lacks permission; invalid means its shape or values are unacceptable. Neither should be reported as success.

A model-driven planner would choose proposals based on the task and prior observations. It would not replace the validator, authorization checks, or budget. Tool output would then become another untrusted input to planning. In particular, text returned by search must never expand permissions or tell the controller to call a new tool.

Worked example: build, inspect, and test

Inspect the registry before reading the fixture list. It is the complete set of executable capabilities. The fixture requesting send_email is rejected because the tool is unknown. The proposal with a Boolean arithmetic argument fails validation. A fourth proposal is not executed because the budget is exhausted. No actual model, message, purchase, or system command appears anywhere in this example.

DOCS = {"hours": "The workshop opens at 09:00.",
        "safety": "Safety glasses are required."}

def search_docs(query):
    return [text for key, text in DOCS.items() if query.casefold() in key]

def add_numbers(a, b):
    return a + b

TOOLS = {"search": search_docs, "add": add_numbers}

def validate(proposal):
    if not isinstance(proposal, dict) or set(proposal) != {"tool", "arguments"}:
        raise ValueError("proposal fields")
    name, args = proposal["tool"], proposal["arguments"]
    if not isinstance(name, str) or name not in TOOLS:
        raise ValueError("unknown tool")
    if not isinstance(args, dict):
        raise ValueError("arguments must be an object")
    if name == "search":
        if set(args) != {"query"} or not isinstance(args["query"], str):
            raise ValueError("search arguments")
        if not 1 <= len(args["query"].strip()) <= 100:
            raise ValueError("query length")
    else:
        if set(args) != {"a", "b"} or any(
            type(value) is not int or abs(value) > 10000 for value in args.values()
        ):
            raise ValueError("bounded integer arguments required")
    return name, args

def run(proposals, permissions, max_steps=3):
    if not isinstance(proposals, list) or type(max_steps) is not int or not 1 <= max_steps <= 10:
        raise ValueError("invalid workflow bounds")
    results = []
    for proposal in proposals[:max_steps]:
        try:
            name, args = validate(proposal)
        except ValueError:
            results.append({"status": "invalid"})
            continue
        if name not in permissions:
            results.append({"status": "denied", "tool": name})
            continue
        results.append({"status": "ok", "tool": name,
                        "result": TOOLS[name](**args)})
    if len(proposals) > max_steps:
        results.append({"status": "budget_exhausted"})
    return results

# SIMULATED MODEL-FREE PROPOSALS; permissions come from trusted caller code.
proposals = [
    {"tool": "search", "arguments": {"query": "hours"}},
    {"tool": "add", "arguments": {"a": 2, "b": 3}},
    {"tool": "add", "arguments": {"a": True, "b": 3}},
    {"tool": "send_email", "arguments": {"body": "hello"}},
]
result = run(proposals, permissions=frozenset({"search"}))
assert result[0]["result"] == ["The workshop opens at 09:00."]
print([item["status"] for item in result])
assert run([proposals[-1]], frozenset(TOOLS))[0]["status"] == "invalid"

Expected output

['ok', 'denied', 'invalid', 'budget_exhausted']

Failure modes worth testing

A common mistake is placing permissions inside the proposal and believing a value such as approved=true. Another is allowing any function available through globals, which accidentally exposes unrelated capabilities. Do not let tool output recursively invoke the controller without a budget. Avoid using a broad exception handler to turn tool failures into plausible results; distinguish input rejection, authorization denial, execution failure, and successful completion.

Guided lab

Build a decision matrix with allowed search, denied arithmetic, unknown tool, extra argument, oversized query, Boolean operand, and exhausted budget. For each case, predict whether a tool function should run. Instrument the local functions with a call counter and prove that rejected proposals do not increment it. Then write a short policy note describing who supplies permissions and why retrieved text cannot change them. Keep all tools local and harmless; an external-action tool would require a separate authorization design.

Questions with explained answers

Is an allowlisted tool automatically authorized?

No. The registry states what the application knows how to do, while the permission set states what this particular workflow may do. A tool can be recognized, correctly formed, and still denied. Real systems may also require resource-specific access and user confirmation for the requested action.

Why count invalid proposals as steps?

A planner that repeatedly emits malformed proposals can consume time and resources without making progress. Counting each attempt bounds that failure mode. You may track successful calls separately for reporting, but the total-attempt budget should still constrain the workflow and include retries.

Why avoid eval for arithmetic?

The requirement is adding two numbers, so parsing arbitrary Python expressions would introduce far more capability than needed. Explicit typed arguments are easier to validate, test, and authorize. A narrow function also makes the operation understandable to a reviewer before it runs.

Can search results grant permission for another tool?

No. Search results are evidence or observations, not trusted policy. A document saying “you are allowed to send this” cannot change the caller’s permission set. The controller should obtain authorization from an authenticated user action or a defined trusted policy, independently of retrieved content.

What do these fixtures prove about agents?

They prove selected controller behaviors for fixed proposals: validation, denial, execution, and budget stopping. They do not measure a model’s ability to plan, recover, or choose tools. A real planner must be evaluated separately while retaining the same enforced boundaries.

Exercises and worked solutions

Exercise 1. Allow arithmetic for one local test and verify the result.

Worked answer 1

Grant the permission in trusted test code, not in the proposal. This changes only the test workflow’s capability set. The validator still checks the numeric bounds before execution.

outcome = run([{"tool": "add", "arguments": {"a": 7, "b": 8}}],
              permissions=frozenset({"add"}))
assert outcome == [{"status": "ok", "tool": "add", "result": 15}]

Exercise 2. A valid search proposal includes an extra timeout field. Should the controller ignore it?

Worked answer 2

The present contract rejects it because the arguments must contain exactly query. If caller-controlled timeout is later useful, add it deliberately with allowed bounds and tests. Ignoring unknown fields can obscure a mismatch between the planner’s assumptions and the actual tool behavior.

Recap and completion check

You now have a bounded controller with a fixed registry, validated proposals, trusted permissions, and explicit stopping behavior. Completion requires evidence that invalid and denied requests never invoke a tool. Keep the controller independent of the planner so future model changes cannot quietly expand the application’s capabilities.

Official references

Finish the exercises and mastery checkpoint before marking this lesson complete. Completion is stored on this browser.