Forward Deployed EngineeringAI EngineeringTool Execution and Reliability
What are the failure modes of tool/function calling, and how do you handle them in production?
Question 48 of 73 · Updated
On this page
- Interview-ready answer
- 1. Understand what function calling actually does
- 2. Failure taxonomy
- 3. Make tool selection and arguments reliable
- 4. Authorization and prompt-injection defense
- 5. Handle failures according to what is known
- 6. Idempotency and ambiguous execution
- 7. Tested Python: argument validation and a bounded recovery policy
- Local execution and verification
- 8. Partial failures and recovery across multiple calls
- 9. Validate tool results and report actual outcomes
- 10. Observability and operational controls
- 11. Production evaluation and fault injection
- 12. Realistic hypothetical FDE scenario
- Likely interviewer follow-ups
- Interview takeaway
Interview-ready answer#
I treat a model's tool call as an untrusted proposed action, not as authorization to execute it. Tool calling can fail before execution, during execution, or after a tool has already produced a side effect.
Before execution, the model may select the wrong tool, invent a tool name, omit required arguments, use valid JSON with incorrect business semantics, or propose an unauthorized operation. I expose a small, relevant tool catalog, validate arguments against a strict schema and business rules, derive identity and tenant scope from trusted session context, and enforce permission and confirmation requirements outside the model.
During execution, I handle timeouts, transient failures, rate limits and unavailable dependencies using deadlines, bounded retries with backoff and jitter, and circuit breakers. For mutations, I use a durable operation identity and downstream idempotency guarantees where supported. A timeout is not proof that the operation failed: the service might have committed before its response was lost. I reconcile ambiguous outcomes using authoritative operation status before reporting success or retrying an unsafe action.
After execution, I validate the result schema, correlate it with the original call, treat returned text as untrusted data, and maintain an explicit workflow state. I verify business outcomes, handle partial failures through supported recovery or compensation, and never let the model invent success.
In production, I monitor tool-selection accuracy, argument validity, permission denials, latency, duplicate effects, ambiguous outcomes and task completion. I test faults and unauthorized requests before rollout. The goal is not merely successful function invocation; it is safe, observable completion of the customer's intended task.
1. Understand what function calling actually does#
A model typically emits a structured proposal consisting of a tool name and arguments. The host application decides whether the proposal can be executed, invokes the tool when allowed, and returns a correlated result. The model can then produce a response or propose another allowed step.
Provider-specific APIs differ in tool definition syntax, streaming behavior, strict schema support, call IDs and result formatting. These differences do not change the central trust boundary: the model proposes; trusted application code validates, authorizes, executes and records the outcome.
Every attempted action is subject to validation and authorization. Passing one call does not grant blanket permission for a later model-generated call.
2. Failure taxonomy#
| Failure mode | Concrete example | Production control |
|---|---|---|
| Incorrect tool selection | Calls cancel_order instead of get_order_status | Relevant tool catalog, task constraints, confirmation for consequential mutations |
| Unknown tool | Invents a function not registered by the application | Exact allowlist lookup; never resolve arbitrary model-generated function names |
| Incomplete output | Streaming response ends halfway through arguments | Buffer and assemble complete calls; reject incomplete or truncated proposals |
| Malformed arguments | Invalid JSON, wrong type or duplicate field | Strict parsing, schema validation, size/depth bounds |
| Semantically wrong arguments | Uses a valid order ID belonging to a different request | Check resource identity, current state and domain rules |
| Unauthorized action | Proposes a mutation the authenticated user cannot perform | Server-side authorization and least privilege |
| Prompt injection | Tool result contains text asking the agent to ignore policy | Treat returned content as data; authorize each subsequent action |
| Schema drift | Tool changes its accepted fields or output shape | Versioned contracts and compatibility tests |
| Transient dependency failure | Service unavailable or throttled | Bounded retries only when safe, backoff, deadline and circuit breaker |
| Ambiguous execution | Response times out after a possible commit | Durable operation identity and authoritative reconciliation |
| Duplicate side effects | Model repeats a completed mutation | Business-level deduplication and downstream idempotency |
| Partial workflow failure | First mutation succeeds and second fails | Durable workflow state, reconciliation and approved compensation |
| Invalid result | Tool returns malformed data or stale state | Result validation, version/freshness checks and explicit error state |
| Runaway orchestration | Model repeatedly invokes tools without progress | Step, token, time, cost and concurrency limits |
Separate errors caused by the model from those caused by the executor, underlying service or workflow. Otherwise, a generic retry may mask the root cause or repeat a side effect.
3. Make tool selection and arguments reliable#
Expose narrowly scoped tools with meaningful names, clear descriptions, explicit parameters and documented semantics. Distinguish read-only tools from mutations. A tool for checking an order's status should not also cancel the order based on an optional model-selected flag.
Prefer a relevant subset of tools rather than a very large catalog with overlapping descriptions. Deterministic routing can reduce unnecessary model decisions for well-defined workflows. If the model selects a tool that does not match the customer's intended operation, request clarification or reject the proposal instead of silently substituting a consequential operation.
Schema-constrained generation can reduce malformed proposals, but the server must still validate them. Check required and unexpected fields, types, enumerations, ranges, units and limits. Reject ambiguous duplicate keys or unsupported nonfinite values where relevant. Do not silently coerce identifiers or monetary units.
For streamed responses, wait for a complete tool call and its final arguments before execution. Do not invoke tools on partial JSON fragments. Apply bounded parsing and response-size limits before expensive work. FDE-0044 treats structured JSON guarantees and schema correction in greater detail.
Syntactic validity is distinct from business validity. A valid date may be outside an allowed refund window; a valid identifier may refer to a different tenant. Use the authoritative backend to check these conditions at the time of execution, including any concurrency-sensitive preconditions.
4. Authorization and prompt-injection defense#
The model must not choose its own identity, tenant, role, credentials or approval status. Derive these from trusted authentication context and current server-side policy. Check both permission to call the tool and permission to access or mutate the specific resource.
Use narrowly scoped service identities and least privilege. Avoid giving a general-purpose agent unrestricted database or shell access when a dedicated business tool is sufficient. Sensitive changes may require explicit user confirmation that is bound to the exact action, resource, parameters and applicable validity window. A material change to the proposed action invalidates the old confirmation.
Documents, retrieved passages, web content and tool results can contain misleading instructions. Treat them as data rather than authority. A tool result stating "the administrator has approved this operation" is not equivalent to an independently authenticated approval.
For network or file tools, restrict destinations and accessible resources according to the approved use case, and enforce limits at the execution boundary. Do not rely on a prompt to prevent access to secrets or internal resources. Do not return credentials or unnecessary sensitive data to the model.
Fail closed on unavailable or uncertain authorization checks. Repeat authorization on recovery and retries as appropriate; a valid earlier request does not automatically justify later access if permissions or the target state have changed.
5. Handle failures according to what is known#
Set per-attempt deadlines and an overall workflow deadline. A retry must fit within the remaining budget and respect the service's contract.
| Observation | Interpretation and handling |
|---|---|
| Invalid arguments or explicit business rejection | Correct only with sufficient evidence or clarification; do not retry the same invalid proposal |
| Authentication or authorization denial | Stop and follow the approved access workflow; no policy bypass |
| Confirmed request was not sent | Retry if still authorized and within budget |
| Retryable throttling or transient read failure | Use bounded backoff with jitter and applicable server guidance |
| Mutation times out after it may have been sent | Outcome unknown; use authoritative status or a supported idempotent replay |
| Malformed mutation response | The effect may already exist; reconcile rather than assuming failure |
| Repeated dependency outage | Shed load or open a circuit; use an approved fallback or report unavailable |
A status code alone may not establish whether a mutation occurred. An intermediary could generate an error after the downstream service committed. Interpret errors according to the service's documented execution semantics.
Backoff reduces load under transient failure but does not make unsafe operations safe. Include maximum attempts, a deadline, jitter, concurrency limits and retry budgets. Avoid nested retry layers multiplying each other's traffic. Circuit breakers protect a degraded dependency; opening a circuit does not resolve already uncertain operations.
Cancellation also needs a precise contract. Stopping the local wait or canceling an asynchronous task does not necessarily cancel a remote operation already accepted by a service. Report the difference between cancellation requested and cancellation confirmed.
6. Idempotency and ambiguous execution#
A common failure sequence is:
- The agent proposes a refund.
- The application sends an authorized refund request.
- The billing service commits it.
- The response is lost.
- The model or host retries the refund.
Without a valid duplicate-prevention mechanism, the customer could be refunded twice.
Use a durable business-operation ID that remains stable across attempts of the same intended action. Bind it to the authorized scope, operation type and canonical parameters. Do not rely only on a model-generated call ID: the model may produce a new call ID when it repeats the same action. Conversely, do not collapse two genuinely distinct user-authorized transactions simply because their parameters match.
Where a downstream service supports idempotency, use the same operation key and equivalent payload for safe retries within the documented scope and retention window. Reject key reuse with conflicting parameters. Confirm the service's exact duplicate-handling and status semantics. A local in-memory set is insufficient across process crashes, multiple workers or remote commit ambiguity.
Durably record the operation before dispatch and maintain its authoritative status or reconciliation evidence. A database transaction that records an intent and an outbox event can coordinate durable local work; it does not make a separate network side effect atomic with that database transaction. The consumer and downstream service still need appropriate deduplication and reconciliation.
The important invariant is that an unknown outcome is not converted to failed or successful without authoritative evidence. If no safe replay or reliable status lookup exists, manual reconciliation may be necessary.
7. Tested Python: argument validation and a bounded recovery policy#
The following dependency-free implementation is educational. It does not execute a real tool, create an idempotency guarantee, or replace service authorization. Its parser accepts only the illustrative ASCII alphanumeric order identifiers defined by this example contract.
PYTHONimport json def parse_args(raw): def unique(pairs): out = {} for k, v in pairs: if k in out: raise ValueError('duplicate key') out[k] = v return out if type(raw) is not str or len(raw.encode('utf-8')) > 4096: raise ValueError('invalid input size') obj = json.loads(raw, object_pairs_hook=unique) if (type(obj) is not dict or set(obj) != {'order_id'} or type(obj['order_id']) is not str or not 1 <= len(obj['order_id']) <= 64 or not obj['order_id'].isascii() or not obj['order_id'].isalnum()): raise ValueError('invalid order arguments') return obj['order_id']
An accepted order ID still needs authorization and existence checks. The parser uses an input byte limit and exact field validation, rejects duplicate object keys, and does not accept a model-supplied tenant override. A full parser boundary must also account for nesting, decoding errors, resource limits and explicit contracts for complex data. This toy schema deliberately does not accept arbitrary identifiers from every possible commerce system.
The next helper represents recovery decisions for one previously authorized business operation. Inputs are trusted executor state and normalized outcome events, not text generated by a model.
PYTHONdef next_action(state, event, retry_safe, attempts_left): if state not in {'ready', 'unknown', 'done', 'failed'}: raise ValueError('invalid state') if event not in {'success', 'rejected', 'not_sent', 'ambiguous', 'inconclusive'}: raise ValueError('invalid event') if type(attempts_left) is not int or attempts_left < 0: raise ValueError('invalid attempt budget') if state in {'done', 'failed'}: return state, 'none' if event == 'success': return 'done', 'report_success' if event == 'rejected': return 'failed', 'report_failure' if event == 'not_sent' and state == 'ready': return ('ready', 'retry') if attempts_left else ('failed', 'report_failure') if retry_safe and attempts_left: return 'unknown', 'retry_same_key' return 'unknown', 'reconcile_or_escalate'
Contract:
- ready means no unresolved previous dispatch; unknown means a previous dispatch may have committed.
- success means authoritative confirmation of the intended operation, not merely a syntactically valid response.
- rejected means authoritative terminal rejection of the entire operation with no unresolved side effect. A later attempt's authorization rejection or conflicting request error cannot establish that an earlier ambiguous attempt never committed.
- not_sent means the executor has evidence that the current attempt was not dispatched. It does not resolve uncertainty inherited from a previous attempt.
- ambiguous and inconclusive do not provide definitive outcome evidence.
- retry_safe is a trusted boolean indicating that replay of the exact same business operation is valid under the downstream idempotency contract. It is not supplied by the model.
- attempts_left counts additional allowed attempts. The calling executor must consume the budget durably and enforce time, policy, payload and key-retention constraints before each retry.
- done and failed are absorbing terminal states in this simplified model; conflicting authoritative results require separate incident reconciliation.
Example outcomes:
PYTHONassert parse_args('{"order_id":"A123"}') == 'A123' assert next_action('ready', 'ambiguous', False, 2) == ( 'unknown', 'reconcile_or_escalate') assert next_action('unknown', 'not_sent', False, 0) == ( 'unknown', 'reconcile_or_escalate') assert next_action('unknown', 'success', True, 0) == ( 'done', 'report_success')
For a bounded JSON payload of length n, parsing and validation require O(n) time and space under ordinary parser/hash-table assumptions, excluding external authorization and lookup. The transition helper performs constant work. In production the challenging work is durable synchronization, concurrency, service-contract validation and recovery across process boundaries.
Local execution and verification#
Python 3.13.5 executed the parser and transition helper on synthetic cases:
- 200 combinations of state, event, retry safety and remaining attempts, compared with independently specified decision rules.
- 7,500 four-event sequences starting in ready or unknown, checking terminal-state preservation, unresolved ambiguity, safe same-key retries and budget consumption.
- 30 structured argument cases, covering types, identifier bounds, unsupported characters and unexpected tenant fields.
- Six malformed or oversized JSON cases, including duplicate keys.
All 7,736 checks passed. These tests cover the local policy and parser. They do not simulate a live distributed service, crash recovery, concurrent workers, real model behavior or a provider's idempotency implementation. A production implementation requires those integration and fault-injection tests separately.
8. Partial failures and recovery across multiple calls#
A multi-tool workflow can fail after an earlier step has succeeded. For example, reserving inventory may succeed while an order confirmation notification fails. Retrying the entire workflow could reserve inventory twice.
Represent workflow stages durably with stable operation IDs, required dependencies, authoritative results and recoverable states. Distinguish not started, pending, completed, definitively failed and uncertain outcomes. Resume from verified state rather than replaying every previous model message.
A saga-style workflow may use compensating operations for completed steps when a later stage cannot be completed. Compensation is a new authorized business action; it is not an automatic rollback of distributed effects. It may fail, may be irreversible, or may require human approval. Define compensation semantics and test them with the service owners.
Parallel calls require attention to conflicting writes and ordering. Independent read-only lookups can often run concurrently. Mutations affecting the same business entity may need serialization, optimistic concurrency checks or explicit workflow coordination. Return tool results correlated with the correct call IDs even when completion order differs from submission order.
Do not allow a model to infer completion of a dependency merely because a previous textual response described an intended action. Use trusted workflow state.
9. Validate tool results and report actual outcomes#
Tool results are another input boundary. Check the response envelope, schema version, correlation identifiers, expected resource, tenant scope and relevant freshness. A successful HTTP response does not necessarily mean the desired business outcome occurred: the service may return an accepted or pending operation rather than completed success.
Treat textual fields as untrusted data. Return the minimum information needed for the task, and do not embed arbitrary internal errors, stack traces or secrets in model-visible responses.
For high-consequence actions, render outcome statements from verified state or enforce a final assertion check. Distinguish the following user-facing results:
- Confirmed complete, with an appropriate receipt or reference.
- Confirmed rejection, with an actionable reason safe to disclose.
- Accepted but pending, with the actual operation status.
- Unable to confirm, with the appropriate reconciliation or escalation path.
Do not claim that a cancellation, refund or update succeeded just because the model emitted a well-formed function call. This is an instance of grounding generated claims in authoritative execution evidence.
10. Observability and operational controls#
Capture correlated traces across model decisions, validation, authorization, executor and downstream calls. Use operation IDs and sanitized error categories, not indiscriminate copies of customer prompts or tool arguments.
| Signal | Why it matters |
|---|---|
| Tool-selection accuracy on labeled cases | Detects routing and description problems |
| Argument validation failure rate by tool/schema version | Detects interface mismatch and malformed proposals |
| Authorization denials and unexpected action proposals | Helps investigate unsafe behavior without bypassing controls |
| Success, definitive failure and uncertain outcomes | Separates actual completion from transport status |
| Retry count and retry amplification | Detects dependency degradation and cascading load |
| Duplicate effect incidents | Direct business reliability indicator |
| Per-stage and end-to-end latency | Distinguishes model, executor and downstream bottlenecks |
| Stuck workflow age and reconciliation backlog | Identifies unresolved customer actions |
| Cost per completed task and step-budget exhaustion | Detects expensive or runaway orchestration |
Set time, step, token, cost and concurrency budgets for agent workflows. Track progress and stop repeated no-progress calls. Apply queue bounds and bulkheads where appropriate. Retain audit evidence according to the customer's data handling policy and restrict access to sensitive traces.
Make alerts actionable: identify the affected tool and operation category, responsible service owner, recovery procedure and scope of potential customer impact.
11. Production evaluation and fault injection#
Use both deterministic integration tests and model-in-the-loop evaluations. The former establish executor invariants independent of the model; the latter measure the frequency and distribution of proposed actions and argument mistakes.
Representative cases include:
- Wrong or nonexistent tool, missing fields, truncated streaming output, unexpected fields, invalid values and duplicate keys.
- Cross-tenant resource references, revoked permissions and missing required confirmation.
- Untrusted instructions in documents or returned tool content.
- Version incompatibility and malformed responses.
- Throttling, transient errors, service outage and exhausted workflow budgets.
- Timeout before dispatch and timeout after commit, duplicate delivery and late results.
- Process crash between dispatch and recording a result, concurrent duplicate attempts and idempotency-key conflict.
- Partial workflow completion, compensation failure and reconciliation delays.
Use approved test environments and synthetic operations rather than creating real customer side effects during fault injection. Verify business invariants, such as a single intended refund never causing two credits, against authoritative service records. An HTTP-success-rate dashboard alone cannot establish this invariant.
For deployment, version tool definitions, validators, execution policy, service adapters and model configuration. Introduce consequential tools gradually using limited authorized cohorts, reviewed operations and known-good rollback paths. A model or prompt change can alter tool behavior even if the API schema remains unchanged.
12. Realistic hypothetical FDE scenario#
A customer support assistant has read-only order status and authorized refund tools. During a refund, the billing API times out.
The executor must not immediately tell the user that the refund failed or ask the model to generate a new refund call. It records the operation as uncertain and attempts to obtain authoritative status. If the service confirms the refund, it reports that result with an appropriate receipt. If the status remains inconclusive, it replays only if the same operation key and unchanged payload are covered by the service's valid idempotency guarantee and the necessary approvals still apply. Otherwise it routes the case to reconciliation.
If the user then asks about a different customer's order, the executor rejects the unauthorized resource access regardless of the model's selected tool. If the refund succeeds but sending a notification fails, the workflow retains the confirmed refund and handles the notification separately rather than refunding again.
This is a hypothetical engineering example. No real customer transaction, refund or external service was invoked.
Likely interviewer follow-ups#
Does strict function calling solve tool reliability? No. It can improve conformance to the provider's supported schema, but cannot guarantee correct intent, authorization, valid business semantics or successful execution.
When is a mutation retry safe? When the executor has evidence that it was not dispatched, or when a verified downstream contract permits replay of the exact same authorized operation. Reconcile ambiguous outcomes instead of guessing.
Is the provider's tool-call ID an idempotency key? Not necessarily. It is useful for correlating protocol messages, but a business operation identity must survive retries and repeated model proposals.
What if two valid tool calls arrive in parallel? Determine whether they are independent. Coordinate conflicting writes and dependencies using application state and concurrency controls.
Can a second model authorize a tool call? A model can help classify or review a proposed action, but authoritative authorization must use trusted identities, policy and business state.
What if the result contains a prompt injection? Treat the content as untrusted data and validate every subsequent action independently. Never let retrieved or tool-generated text override system policy.
What is the most important metric? The customer's correctly completed task without unauthorized or duplicate effects. Tool-call success rate is only one diagnostic component.
Interview takeaway#
Model tool calling is a proposal-and-execution protocol. Validate intent and arguments, enforce authorization outside the model, make recovery depend on authoritative execution evidence, and bound retries and workflow resources. Protect business operations with durable identity, idempotency where supported and explicit reconciliation. Report only confirmed outcomes and evaluate the complete production workflow under failure.
References
- 1.OpenAI — Function calling (not live-verified)platform.openai.com
- 2.JSON Schema — Understanding JSON Schema (not live-verified)json-schema.org
- 3.
- 4.
- 5.
- 6.OpenTelemetry documentation (not live-verified)opentelemetry.io
- 7.Python json documentation (not live-verified)docs.python.org
Related questions
Explore other topics:AI AgentsAI System DesignLarge Language Models