Tool Calling in LLM Apps: Schemas, Validation, Permissions, and Retry Patterns
tool callingAI agentsfunction callingJSON SchemaLLM APIs

Tool Calling in LLM Apps: Schemas, Validation, Permissions, and Retry Patterns

PPrompt Dev Hub Editorial Team
2026-11-14
9 min read

A practical guide to dependable LLM tool calling, covering schemas, validation, permissions, retries, execution, errors, and audit reviews.

Dependable tool calling starts with more than a well-written prompt. This guide explains how to compare and implement LLM tool-use patterns, from JSON Schema design and argument validation to permissions, retries, parallel execution, error handling, and audit logging. It also provides a recurring review process for keeping an AI agent reliable as models, SDKs, tools, and business rules change.

Overview

Tool calling allows an LLM application to request an action from software outside the model, such as searching a knowledge base, checking an order, creating a calendar event, or calculating a value. The model proposes a tool name and arguments; your application decides whether the request is valid and permitted, executes the operation, and returns a result for the model to use.

The important design boundary is that the model should propose actions, not receive unrestricted authority to perform them. Your application remains responsible for schema validation, authentication, authorization, rate limits, timeouts, retries, side-effect controls, and logging. This separation makes tool use easier to test and safer to operate in production LLM apps.

A useful implementation usually has five layers:

  1. Tool contract: a narrow name, description, input schema, and output shape.
  2. Orchestrator: the code that sends available tools to the model and processes tool calls.
  3. Policy layer: permission checks, user confirmation, data-access rules, and limits.
  4. Execution layer: the actual API, database, or service operation.
  5. Observability layer: structured logs, traces, metrics, and replayable test cases.

For broader application context, compare this workflow with the patterns in LLM Tool Calling Examples and the security controls in the LLM Application Security Checklist.

What to track

1. Tool schemas and argument quality

A tool schema is an interface, not merely documentation. Give each tool one clear purpose and define arguments that the application can validate deterministically. Prefer enumerated values, bounded numbers, explicit required fields, and structured objects over a single free-form text parameter.

A provider-neutral JSON Schema pattern might look like this:

{
  "name": "lookup_order",
  "description": "Retrieve the status of an order the current user is allowed to view.",
  "parameters": {
    "type": "object",
    "properties": {
      "order_id": {
        "type": "string",
        "minLength": 1,
        "maxLength": 64
      },
      "include_items": {
        "type": "boolean",
        "default": false
      }
    },
    "required": ["order_id"],
    "additionalProperties": false
  }
}

Track schema changes as carefully as API changes. Record the version, owner, intended behavior, allowed values, and whether the tool can create an external side effect. A model may produce syntactically valid JSON that is still semantically wrong, such as an order identifier belonging to another user or a date outside the supported range. Validate both.

2. Validation and malformed calls

Do not send model-produced arguments directly to a database or external service. Parse the call, validate its structure, normalize safe values, and apply business rules before execution. If parsing fails, treat the event as a recoverable tool error rather than allowing an exception to terminate the entire conversation.

A compact orchestration pattern is:

for call in model_response.tool_calls:
    tool = registry.get(call.name)
    if tool is None:
        return tool_error(call.id, 'Unknown tool')

    args = parse_json(call.arguments)
    if args.failed:
        return tool_error(call.id, 'Arguments were not valid JSON')

    result = validate_and_authorize(tool, args.value, request_context)
    if result.rejected:
        return tool_error(call.id, result.reason)

    output = execute_with_limits(tool, result.value)
    record_audit_event(call, result.value, output)
    return tool_result(call.id, output)

The exact SDK syntax varies by provider, but this control flow is portable. Keep validation outside the prompt so a model cannot override it by claiming that a restriction no longer applies.

3. Permissions and confirmation

Classify tools by risk before exposing them to an agent. Read-only operations, such as searching documentation, generally need different controls from actions that send messages, change records, issue refunds, or delete data. Use the current user, tenant, role, resource owner, and requested operation as inputs to authorization.

For consequential actions, require an explicit confirmation step or a human approval path. The confirmation should identify what will happen, which resource will be affected, and any material parameters. Avoid treating the model’s statement that a user approved an action as proof of approval; record approval in an application-controlled state.

Prompt injection is especially relevant when tool arguments or instructions come from retrieved documents, web pages, emails, or user-provided files. The RAG chatbot architecture guide can help with the retrieval side, while permissions must still be enforced by application code.

4. Sequential and parallel execution

Sequential tool use is appropriate when one result supplies an argument for the next operation. For example, an agent might search for a customer, inspect the matching account, and then prepare a support response. Pass only the minimum required result between steps, and place a maximum on the number of turns or calls.

Parallel execution can reduce latency when calls are independent, such as retrieving account preferences and checking service status. It also introduces coordination concerns: one call may fail while others succeed, results may arrive in a different order, and several calls may contend for the same resource. Assign every call an identifier, preserve that identifier in the returned tool result, and define whether partial success is acceptable.

Before enabling parallel calls, track whether each tool is read-only, idempotent, rate-limited, or state-changing. Do not parallelize operations merely because the model requested multiple calls.

5. Timeouts, retries, and idempotency

Every tool needs a timeout appropriate to its operation. A short read request and a long-running export should not share an unexamined default. When a timeout occurs, return a bounded error to the model and decide whether the user should see a retry option.

Retry only errors that are plausibly transient. Use exponential backoff with a maximum attempt count, and avoid retrying invalid arguments, authorization failures, or deterministic business-rule violations. For state-changing tools, use an idempotency key so a network failure does not cause a second execution when the first request actually succeeded.

attempt = 0
while attempt < MAX_ATTEMPTS:
    response = call_service(tool, args, idempotency_key)
    if response.success or not response.retryable:
        break
    sleep(backoff(attempt))
    attempt += 1

Return errors in a form the model can understand without exposing secrets, stack traces, internal hostnames, or unnecessary personal data. Distinguish messages such as invalid argument, not authorized, temporarily unavailable, and requires confirmation. This gives the model a chance to ask for clarification or explain the limitation accurately.

6. Audit logs and evaluation signals

For each call, record a correlation ID, user or service context, conversation or request ID, tool name and version, validated arguments after redaction, authorization outcome, start and end times, retry count, result status, and error category. Apply retention and access controls appropriate to the data involved.

Do not log secrets or unrestricted raw inputs by default. A useful audit record supports debugging without becoming a second source of sensitive data. Track operational measures such as tool-call success rate, validation rejection rate, timeout rate, duplicate execution rate, latency, and cost. Pair these with quality checks: did the agent choose the right tool, supply the correct arguments, respect permissions, and explain failures properly?

Regression cases belong in your normal development process. The prompt testing framework guide offers a useful model for organizing fixtures and CI checks. Include adversarial cases, malformed JSON, missing fields, ambiguous user requests, expired permissions, and provider response changes.

Cadence and checkpoints

Tool calling should be reviewed on a recurring schedule rather than only after an incident. A monthly operational check can focus on failures and latency. A quarterly design review can examine schemas, permissions, model behavior, and whether each tool is still necessary.

  • Monthly: review error categories, timeouts, retries, authorization rejections, unusual call volume, and the most common malformed arguments.
  • Quarterly: review tool ownership, schema versions, permission rules, confirmation flows, audit-log coverage, and test-case results.
  • Before a model or SDK upgrade: replay representative conversations, parallel-call scenarios, malformed-call cases, and high-risk actions in a staging environment.
  • After a tool change: compare the old and new contract, update fixtures, verify backward compatibility where needed, and confirm that downstream consumers handle new error shapes.
  • After an incident: preserve the relevant trace, identify whether the failure came from selection, arguments, authorization, execution, or presentation, and add a regression test.

Keep a small tool inventory with columns for owner, purpose, risk class, schema version, side effects, authentication method, timeout, retry policy, data sensitivity, and last review date. This is more useful than relying on memory or scattered SDK configuration.

How to interpret changes

A higher tool-call success rate is not automatically an improvement. If validation rejections fall because the application silently accepts unsafe or incomplete arguments, the metric is moving in the wrong direction. Interpret operational data alongside correctness and security checks.

Use a failure taxonomy to locate the layer that needs attention:

  • Selection failure: the model chose an unsuitable tool or acted without using one.
  • Schema failure: the call was missing fields, used the wrong type, or included unsupported properties.
  • Policy failure: the request was not authorized or required confirmation.
  • Execution failure: the underlying service timed out, rejected the request, or returned an unexpected response.
  • Presentation failure: the tool succeeded, but the model misunderstood or inaccurately summarized the result.

When a model upgrade changes behavior, first compare tool descriptions, schemas, and orchestration prompts before changing business logic. A more capable model may call tools more often, attempt parallel execution, or produce different optional fields. Conversely, a smaller or lower-cost model may need narrower tool descriptions, stronger examples, or more deterministic routing. Use the LLM model selection guide and LLM cost optimization guide when evaluating that trade-off.

When comparing providers or AI dev tools, compare the complete workflow rather than a single function-calling demo. Check schema support, structured output behavior, streaming semantics, parallel-call handling, error representation, observability, SDK stability, and the amount of provider-specific code your team must maintain. A tool that looks convenient in a prototype may be harder to govern at production scale.

When to revisit

Revisit this implementation whenever you add a tool, change a schema, introduce a side effect, modify a permission rule, switch models, update an SDK, or connect a new data source. Also schedule a formal monthly or quarterly review even when the system appears stable; quiet failures can remain hidden when only successful user journeys are monitored.

Use this practical checklist before releasing a change:

  1. Write a narrow tool description and define a versioned JSON Schema.
  2. Reject unknown tools, malformed JSON, unsupported fields, invalid values, and unauthorized resources.
  3. Separate read-only tools from state-changing tools and add confirmation where the risk warrants it.
  4. Set explicit timeouts, bounded retries, and idempotency controls for side effects.
  5. Define how sequential, parallel, partial-success, and duplicate-call cases are handled.
  6. Return safe, typed tool errors that help the model recover without revealing internal details.
  7. Record a redacted audit event for every attempted call.
  8. Replay normal, malformed, adversarial, and permission-boundary test cases.
  9. Review the results monthly and update the inventory, regression suite, and runbook.

Reliable AI agent tool use is an operating practice, not a one-time prompt change. Treat each tool as a governed software interface, measure its behavior over time, and make model or SDK upgrades pass the same validation and permission checks as any other production change.

Related Topics

#tool calling#AI agents#function calling#JSON Schema#LLM APIs
P

Prompt Dev Hub Editorial Team

AI Development Editor

Senior editor and content strategist. Writing about technology, design, and the future of digital media. Follow along for deep dives into the industry's moving parts.