smartyfy.mrindigi.com

AI & Machine Learning Master Course — 137. Tools, structured outputs, and constrained actions

Smartyfy AI & Machine Learning Master Course

Course ID: smartyfy-ai-ml-master-200

Lesson 137: Tools, structured outputs, and constrained actions

Prerequisites: Lesson 136. Learning outcome: Design validated tool interfaces and authorization boundaries.

A proposed tool call is data until validated

A model can produce a proposed action containing a tool name and arguments. The application decides whether that proposal is well formed, meaningful, authorized, and safe to execute. Generating a plausible call does not create permission, and a schema-valid call can still request an action the user never authorized.

Separate the proposal stage from execution. A small read-only lookup interface is easier to constrain than a generic command runner. Prefer a finite allowlist of narrowly defined operations with explicit inputs and outputs. The application should choose the authority associated with the request from trusted session state, not from a model-written field claiming an administrator role.

This lesson implements only an in-memory read-only lookup. No external service, file mutation, shell command, or real user data is involved. The same boundary principles become more important when a system can send messages, spend money, or change records.

Syntax, schema, semantics, and authorization are separate checks

Parsing asks whether a response can be read as the chosen data format. Schema validation asks whether expected fields and types are present and whether unwanted fields are prohibited. Semantic validation asks whether values make sense for the operation. Authorization asks whether the caller may perform that operation on that resource.

For example, a JSON object can parse correctly while its document ID is an integer instead of the required string. A correctly typed ID can refer to an unknown record. A known record can still be outside the caller’s permitted set. These failures should not be collapsed into a single assumption that “valid JSON means execute.”

JSON Schema can express required properties, type constraints, enumerations, and restrictions on additional properties. Merely listing properties does not automatically require them or prohibit other keys. The lab uses explicit Python checks for its tiny contract instead of installing a schema library. It is not a complete general-purpose JSON Schema implementation.

Constrain the interface and its effects

Our proposal has exactly two top-level fields: tool and arguments. The only allowed tool is lookup. Its arguments object has exactly one field, document_id, whose value must be a string. The caller’s allowed document IDs arrive separately through trusted application state.

The execution order is parse, structural checks, permission check, then record lookup. Checking permission before revealing whether a private record exists can reduce unnecessary information exposure. Returned status values distinguish malformed or unauthorized proposals from an authorized but missing record.

For mutating tools, additional controls may include confirmation, bounded parameters, transactional validation, and idempotency. An idempotency key can help avoid duplicate effects when a request is retried, but it is not a substitute for authorization. A timeout leaves execution outcome uncertain; do not blindly repeat an operation that might already have completed.

CPU lab: reject three different invalid proposals

The local catalog contains one fictional document. Four fixture proposals test a permitted lookup, an unsupported delete tool, a lookup without resource permission, and a lookup with an integer ID. The recorded statuses are ok, rejected, rejected, rejected, with reasons schema, unauthorized, and schema for the failures.

The code verifies that the catalog remains unchanged. It never interprets tool names as Python functions through eval or passes arguments into a shell. Instead, a fixed branch implements the one allowed operation. The example is a validator and dispatcher, not a language-model tool-calling experiment.

Save example137.py as a helper for the following security lesson. Its demonstration tests are protected by a main guard, so importing execute does not rerun them. Real deployment would also require request-size limits, logging controls, authentication integration, and an explicit policy for duplicate JSON keys and parser edge cases. Those controls are not claimed to be implemented here.

import json
catalog={'doc-1': 'The fictional garden store closes at 17:00.'}

def execute(raw, allowed_ids):
    try:
        p=json.loads(raw)
    except json.JSONDecodeError:
        return {'status':'rejected','reason':'invalid_json'}
    if not isinstance(p,dict) or set(p)!={'tool','arguments'}:
        return {'status':'rejected','reason':'schema'}
    a=p['arguments']
    if p['tool']!='lookup' or not isinstance(a,dict) or set(a)!={'document_id'}:
        return {'status':'rejected','reason':'schema'}
    doc_id=a['document_id']
    if not isinstance(doc_id,str):
        return {'status':'rejected','reason':'schema'}
    if doc_id not in allowed_ids:
        return {'status':'rejected','reason':'unauthorized'}
    if doc_id not in catalog:
        return {'status':'not_found'}
    return {'status':'ok','text':catalog[doc_id]}

if __name__ == '__main__':
    cases=[('{"tool":"lookup","arguments":{"document_id":"doc-1"}}',{'doc-1'}),
           ('{"tool":"delete","arguments":{"document_id":"doc-1"}}',{'doc-1'}),
           ('{"tool":"lookup","arguments":{"document_id":"doc-1"}}',set()),
           ('{"tool":"lookup","arguments":{"document_id":7}}',{'doc-1'})]
    results=[execute(raw,allowed) for raw,allowed in cases]
    print('Statuses:',[r['status'] for r in results])
    print('Rejection reasons:',[r.get('reason') for r in results[1:]])
    assert [r['status'] for r in results]==['ok','rejected','rejected','rejected']
    assert catalog=={'doc-1': 'The fictional garden store closes at 17:00.'}

Validate results and keep a bounded control loop

Tool outputs can contain untrusted text too. A lookup result should not be promoted into an instruction that changes the caller’s authority. Preserve the distinction between structured status, source content, and application policy when returning results to a model.

A multi-step assistant needs limits on tool calls, elapsed time, result size, and repeated failures. Otherwise a harmless-looking loop can consume resources or repeatedly attempt rejected actions. Decide what the application should do after an invalid proposal: ask for a corrected proposal, return a clear error, or stop. The decision should be bounded rather than an unlimited retry cycle.

Audit logs should capture enough to explain which operation was requested, which resource was authorized, and what outcome was confirmed. Avoid unnecessarily storing private document contents or secrets. A successful tool status proves only the operation’s stated outcome; a model’s later natural-language summary can still misdescribe it and may need checking.

Four practice questions with worked answers

Practice 1

A proposal is valid JSON but names delete, which is not allowed. What happens?

Answer: It fails the tool allowlist check and is rejected before any action. Parsing success does not expand the interface or authorize a different operation.

Practice 2

Why are allowed document IDs passed separately from the proposal?

Answer: They represent trusted application permission state. If the proposal could grant itself access by supplying its own allowed list, a model or attacker could bypass the authorization boundary.

Practice 3

A write request times out after transmission. Why is an immediate identical retry risky?

Answer: The first request may already have taken effect. Repeating it can duplicate a consequential action. Check the outcome or use a correctly implemented idempotency mechanism within the authorized operation.

Practice 4

Does this lab fully implement production tool security?

Answer: No. It demonstrates a narrow schema, allowlist, resource permission check, and read-only dispatcher. Authentication, parser hardening, request limits, and operational logging policies remain separate requirements.

Five multiple-choice questions

Question 1

What does schema validity establish?

  • A. That the proposal matches specified structural constraints.
  • B. That executing the proposal will achieve the user’s intended outcome.
  • C. That the user authorized every requested resource.

Correct: A. Structure is only one layer. Authorization and task correctness require separate evidence.

Question 2

Where should the resource permission set come from?

  • A. A field written by the model inside the action proposal.
  • B. Instructions found in the retrieved document text.
  • C. Trusted application context.

Correct: C. Authority must be established outside untrusted proposals and source content. Neither can grant itself permissions.

Question 3

Which proposal succeeds in the fixture?

  • A. Lookup of doc-1 when doc-1 is explicitly allowed.
  • B. Delete of doc-1 because the document exists.
  • C. Lookup of doc-1 with an empty allowed-ID set.

Correct: A. The operation, argument type, and resource permission all pass. Existence alone does not authorize deletion or access.

Question 4

Why use an idempotency mechanism for some mutating operations?

  • A. To prove that a timed-out request never reached the service.
  • B. To help prevent duplicate effects when an authorized request is retried.
  • C. To let any caller skip resource permission checks.

Correct: B. Idempotency addresses repetition, not authorization or certainty about a timeout’s cause.

Question 5

What should happen to instructions embedded in a lookup result?

  • A. Use them to replace the caller’s trusted permission set.
  • B. Allow them to extend the tool allowlist for that result only.
  • C. Treat them as source data rather than new execution authority.

Correct: C. Tool-returned content can be untrusted. It does not redefine application policy or caller permissions.

Common pitfalls

Avoid equating JSON with permission, letting proposals self-assign roles, invoking arbitrary code from tool names, or blindly retrying uncertain writes. Validate input, authority, effect, and returned evidence as distinct concerns.

Summary

A reliable tool interface separates model proposals from trusted execution. Narrow schemas, operation allowlists, resource checks, bounded retries, and clear result contracts make actions inspectable without granting authority to generated text.

Primary sources and further reading