← Back to learning path
Chapter · Published

Tool calls and function contracts: keep agents controllable

Design tool schemas, error responses, and idempotency rules to reduce argument drift and side effects.

Source: knowledge/p24-b/collection_8023a8d754046b6c2ae7220f/tutorials/agent-tool-contracts-and-function-calling.mdAI agent engineering
Chapter progress 0%Learning path progress 0% · 0/10 chapters completedContinue learning path →

Tool calls are the boundary between an agent and a real system. As the tool set grows, names, arguments, permissions, timeouts, and errors should become stable contracts rather than natural-language conventions in a prompt.

Core concepts

Classify tools as read-only, writable, or high risk. Read-only tools may run automatically; writable tools need an idempotency key; high-risk tools must return a confirmation state. Distinguish invalid input, permission failure, temporary dependency failure, and business rejection.

from dataclasses import dataclass

@dataclass(frozen=True)
class SearchArgs:
    query: str
    limit: int = 10

def validate(args: SearchArgs) -> None:
    if not args.query or len(args.query) > 120:
        raise ValueError('invalid query')
    if not 1 <= args.limit <= 50:
        raise ValueError('invalid limit')

def tool_result(ok: bool, code: str, data: dict | None = None) -> dict:
    return {'ok': ok, 'code': code, 'data': data}

Steps

  1. Write a versioned schema for every tool, including required fields and maximum lengths.
  2. Validate the schema after parsing model output and before the actual call.
  3. Compute an idempotency key for writes. A duplicate request returns the first result without repeating the side effect.
  4. Map tool errors to short model-facing codes and keep detailed stack traces in restricted logs.

When to use it

This approach suits CRM queries, inventory reads, internal knowledge search, and workflows that need approval.

Common questions

How do I keep a schema change compatible? Add optional fields; use a new tool name or version for a breaking change.

What happens on a timeout? Return a clear temporary_unavailable code and cap retries.

Should every error be sent to the model? Return only what is necessary. Do not expose permissions or internal paths.

Official references

OpenAI Function Calling; OpenAI Structured Outputs.

Last checked: 2026-11-16. Use the linked official documentation for current versions and interfaces.

Related practical cases

KnowledgeCase study: an evidence package and human handoff after an agent failure

Further reading

KnowledgeAI Agents: From Core Concepts to ProductionKnowledgeDesigning Reliable AI Automation WorkflowsKnowledgeStructured Outputs and Tool Contracts for Safe Agents
Product Hub Demo · V0.3