groundy
Agents & Frameworks

Function Calling Best Practices: LLMs That Actually Use APIs Correctly

Make LLM function calling reliable in production with clear schemas, structured outputs, careful error handling, and validation that rejects malformed or unauthorized calls.

Published Updated 10 references
On this page19 sections

A dependable function-calling setup separates three questions: Did the arguments match the schema? Did the model choose appropriate values? Is this particular call allowed to execute? With a supported schema and configuration, strict mode can answer the first question. It cannot answer the other two. Production reliability comes from constrained decoding, clear tool design, and application-side validation and authorization working together.

What is Function Calling?

Function calling (also known as tool calling) provides a mechanism for large language models to interface with external systems, databases, and APIs. When implemented carefully, it extends LLM capabilities beyond their training data, enabling dynamic data retrieval, action execution, and multi-step workflows. Production implementations still encounter reliability problems ranging from invented parameters to schema violations and unauthorized operations.

According to OpenAI’s documentation, the pattern involves five high-level steps: providing tool definitions to the model, receiving tool call requests, executing the function logic on the application side, returning results to the model, and receiving the final response or further tool calls (OpenAI. “Function Calling Guide.”).

A function tool is defined by a JSON schema specifying its name, description, and parameters. When the model decides to use it, the model returns structured arguments rather than executing the function itself. Your application remains responsible for execution, which creates an essential security and control boundary.

Anthropic distinguishes client tools, which run in your application, from server tools, which run on Anthropic’s infrastructure. Client tools include functions you define and tools such as bash and text_editor; server tools include web search, web fetch, code execution, and tool search. Client tools return a tool_use block that your code handles. Server-side execution is handled by Anthropic, unless Claude calls a server tool in the same group of parallel tool calls as one of your client tools, in which case your code handles that execution too (Anthropic. “Tool Use Overview.”). This distinction determines what your code must execute, secure, and observe.

How Does Function Calling Work?

The implementation follows a conversational pattern that maintains state across API calls. When a user sends a prompt that might require external data, the application sends both the user message and available tool definitions to the LLM.

The model assesses whether a tool can help. With Claude, a client tool request produces a stop_reason of tool_use and one or more tool_use blocks. The application extracts the tool name and input, executes the operation, and returns the result in a tool_result block (Anthropic. “Tool Use Overview.”).

OpenAI’s documentation illustrates the boundary with a get_weather tool. Given a question about Paris, the model can request get_weather with Paris as the location argument rather than inventing a temperature. Your application retrieves the real observation, returns it as the tool output, and lets the model compose the final answer (OpenAI. “Function Calling Guide.”).

For reasoning models, preserve any response items that the API requires alongside tool outputs. OpenAI specifically notes that reasoning items returned with tool calls must also be passed back; dropping them can break the state on which the tool request depends.

Function calling earns its overhead when current data or real actions matter

Functions can retrieve current stock prices, weather, calendar availability, and database records instead of relying on training data. They can also send emails, create calendar events, process refunds, or update records. Those actions need stronger authorization and confirmation controls than read-only lookups. A multi-step process can be divided into discrete functions that the LLM selects based on context. In multi-agent systems, tools can also expose one agent’s capabilities to another.

The extra machinery is not always justified. In Anthropic’s work with dozens of teams building LLM agents, the most successful implementations reportedly used simple, composable patterns rather than unnecessarily complex frameworks (Anthropic. “Building Effective Agents.”).

Common Failure Modes and Reliability Patterns

Production function calling faces several predictable failure modes. They need different defenses rather than one larger prompt.

Schema Violations and Type Errors

Without structured outputs, LLMs can generate malformed JSON or invalid tool inputs. Anthropic identifies parsing errors, missing required fields, inconsistent data types, and other schema violations as expected problems without enforcement (Anthropic. “Structured Outputs.”).

The structural part of the solution is constrained decoding. Anthropic’s structured outputs feature constrains responses to a schema, while strict: true on a tool guarantees schema validation for tool names and inputs (Anthropic. “Structured Outputs.”). OpenAI’s strict mode similarly makes function calls adhere to the supplied schema instead of treating it as best effort (OpenAI. “Function Calling Guide.”).

OpenAI strict mode has concrete schema requirements: every object must set additionalProperties to false, and every field in properties must be listed as required. Optional values can be represented with a nullable type. Some JSON Schema features remain unsupported.

Do not assume that using a particular API automatically enables enforcement. If strict is omitted, OpenAI Responses requests attempt to normalize the schema into strict mode when possible, but fall back to non-strict function calling when they cannot; the returned tool then shows strict: false. Chat Completions remains non-strict by default. Set strict explicitly when you depend on the guarantee, and test that your schema is accepted (OpenAI. “Function Calling Guide.”).

Schema validity is still not semantic correctness. A schema can require a location string while accepting the wrong city, an outdated identifier, or a value the user never supplied.

Hallucinated Parameters

LLMs may invent parameter values when user input is ambiguous. Microsoft recommends explicitly instructing the model not to assume values and to ask for clarification when a request is ambiguous (Microsoft. “How to use function calling with Microsoft Foundry Models.”).

For a weather request with no location, the desired behavior is a clarification question, not a plausible default city. For consequential actions, enforce the same boundary in application code: if required information is missing or unconfirmed, do not execute the operation merely because the model produced a valid call.

Error Handling Patterns

Return failures to the model as concise tool results rather than crashing the conversation. A useful error says what failed, whether the caller can correct it, and whether retrying is appropriate. Avoid returning secrets, stack traces, or unnecessary internal details.

Retry transient failures selectively: Network timeouts and temporary service failures may justify exponential backoff with a capped attempt count. Validation failures and permission denials should not be retried blindly. For side-effecting operations, use an idempotency mechanism where the underlying API supports one so a retry does not repeat the action.

Validate before execution: Check that the function name is allowlisted, the arguments satisfy business rules, and the caller is authorized for this particular action.

Limit the blast radius: Microsoft recommends validating calls, using trusted data and tools, applying least privilege, and adding user confirmation for actions with real-world effects. It also warns that untrusted content in a function result can steer subsequent model behavior (Microsoft. “How to use function calling with Microsoft Foundry Models.”). Database credentials, refund permissions, and messaging access should therefore be narrower than the application’s general privileges.

Schema Design Best Practices

Effective function schemas balance expressiveness with predictable use. Current OpenAI and Anthropic guidance supports several practical approaches.

Function Naming Conventions

Use descriptive, action-oriented names that distinguish the operation from similar tools. Prefer get_current_weather over weather or fetch_data. Use the system prompt and function description to explain when the tool should and should not be called.

Parameter Design

ApproachBenefitTrade-off
Required, non-null fieldsMakes essential inputs explicitMissing information may require clarification before a call
Nullable fields in a strict schemaRepresents optional values while satisfying strict-schema rulesApplication code must handle null deliberately
Enum constraintsPrevents values outside a fixed setPoor fit for open-ended or frequently changing inputs
Nested objectsRepresents structured relationshipsRequires validation of relationships between fields, not just types

OpenAI also recommends using enums and object structure to prevent invalid states, avoiding arguments your application already knows, and combining functions that are always called in sequence. If an order_id is already available in application state, for example, passing it in code removes one opportunity for the model to supply the wrong identifier (OpenAI. “Function Calling Guide.”).

Description Quality

Parameter descriptions should include:

  • What the parameter represents
  • Its expected format, with an example where useful
  • Constraints or valid values
  • How to infer it from context, or when to ask instead
  • How the parameter differs from similarly named fields

Anthropic’s weather example uses "description": "City and state, e.g. San Francisco, CA" (Anthropic. “Tool Use Overview.”). The combination of meaning and concrete format is more useful than a label such as location alone.

Keep the initial tool set small

Tool definitions consume context and are billed as input tokens. OpenAI’s soft guideline is fewer than 20 initially available functions at the start of a turn, accompanied by an explicit recommendation to evaluate performance with different tool counts (OpenAI. “Function Calling Guide.”).

For larger catalogs, OpenAI supports namespaces for grouping related tools and tool_search for deferring tools until the model needs them. The guide limits tool_search support to gpt-5.4 and later models. This changes the design choice: you do not necessarily need to place every schema in the initial request, but you do need to test whether the model discovers and loads the right tool.

Parallel vs. Sequential Function Calls

Some models support parallel function calling, allowing multiple independent calls in one response. Microsoft’s examples show several location lookups returned together, reducing the number of API round trips (Microsoft. “How to use function calling with Microsoft Foundry Models.”).

Sequential calling is required when:

  • One function’s output is another’s input
  • Operations have side effects that must complete in order
  • Rate limits or resource constraints require throttling
  • A later action depends on validating or authorizing an earlier result

Schema compliance does not establish multi-step correctness. In IBM Research’s NESTful benchmark, evaluated models struggled more as nesting deepened and data dependencies increased, and even the strongest tested results left substantial room for improvement. Those findings belong to the models and prompting setups evaluated, not a ranking of current APIs. The practical lesson is to test variable passing, execution order, and final outcomes, not just whether each JSON object parses.

Comparison: Native APIs vs. Framework Abstractions

Developers can use provider APIs directly or adopt a framework that abstracts tool definitions, dispatch, and conversation state.

FactorNative APIFramework abstraction
ControlDirect visibility into prompts, schemas, and responsesAbstractions can obscure individual requests and responses
DebuggingDirect access to request and response dataDepends on the framework’s tracing and access to raw calls
FlexibilityCustom execution and recovery logicCommon patterns are easier, but provider-specific behavior may be hidden
Learning curveRequires understanding each provider’s APICan reduce initial setup work
PortabilityProvider-specific integration codeA shared interface can help, but schemas and capabilities still differ

Anthropic advises starting with direct LLM API calls because many patterns can be implemented in a few lines of code. It also warns that abstraction layers can obscure prompts and responses, and that incorrect assumptions about the underlying implementation are a common source of customer error (Anthropic. “Building Effective Agents.”).

Start directly unless a framework solves a requirement you have already identified, such as multi-provider routing or tracing. This mirrors sound prompt engineering practice: understand the mechanism before adding another layer around it.

API Evolution: What Changed in 2025–2026

If you’re referencing documentation written before mid-2025, several API details now need another look.

OpenAI: functions is deprecated, tools is the standard

In Chat Completions, the functions and function_call parameters are deprecated. Use tools and tool_choice instead (Microsoft. “How to use function calling with Microsoft Foundry Models.”).

OpenAI launched the Responses API in March 2025 and subsequently added built-in tools and remote MCP server support (OpenAI. “New tools and features in the Responses API.”). Responses is the better default for new OpenAI agent projects, but it does not eliminate your execution loop for custom functions. Your application still receives function calls, executes the permitted code, and returns the outputs.

Model compatibility also matters. OpenAI’s current guide states that GPT-6 Astra and GPT-6.1 Sol require Responses for tool calling (OpenAI. “Function Calling Guide.”).

Anthropic: strict: true replaces prompt-based schema enforcement

Prompting the model to ask for clarification remains a behavioral guardrail, but it is not schema enforcement. Anthropic separates JSON outputs, configured through output_config.format, from strict tool use, enabled with strict: true. The two features can be used independently or together, and Anthropic now marks structured outputs as stable (Anthropic. “Structured Outputs.”).

Support varies by model and platform. Anthropic’s documentation lists per-platform status for deployments including Claude Models on Google Cloud and Microsoft Foundry, so check the current compatibility table for your model and deployment before relying on strict tool use or JSON outputs (Anthropic. “Structured Outputs.”). Compatibility establishes feature availability, not a ranking of function-calling accuracy. Evaluate candidate models on your own schemas, ambiguous requests, and multi-step tasks.

Vendor launch evidence needs the same scoping. Anthropic reported that early testers found Opus 4.8 more likely to flag uncertainties, while its evaluations found the model around four times less likely than Opus 4.7 to let flaws in written code pass unremarked (Anthropic. “Claude Opus 4.8.”). Those are vendor-reported behavior and coding results, not direct measurements of invented tool parameters.

Enforcement layerWhat it establishesWhat remains your responsibility
Strict tool use or structured outputsArguments conform to the accepted schemaWhether the values are correct and appropriate
System prompt and tool descriptionsWhen to call, abstain, or ask for clarificationHandling cases where behavior diverges from instructions
Server-side validation and authorizationWhether this call may execute in this contextSecure credentials, business rules, and recovery

All three layers are complementary. Schema enforcement catches structural errors; prompts shape model behavior; application controls guard real systems.

The Model Context Protocol (MCP) Standard

The Model Context Protocol is an open-source standard for connecting AI applications to external systems. Its documentation describes it as “like a USB-C port for AI applications” and as a standardized way to connect to data sources, tools, and workflows (Model Context Protocol. “Introduction to MCP.”). MCP can reduce integration work through standardized connections and a broad ecosystem of compatible clients and servers.

OpenAI’s Responses API also supports remote MCP servers, allowing an application to connect models to tools hosted on those servers (OpenAI. “New tools and features in the Responses API.”). This makes an MCP server reusable across compatible applications, but it does not remove the need to test each model’s tool selection or to configure authentication, permissions, and error handling. MCP standardizes the connection; it does not decide whether a requested action is correct or safe.

Production Checklist

Before deploying function calling, verify:

  • Function names and parameter descriptions explain purpose, format, constraints, and edge cases
  • Strict mode or structured outputs is explicitly enabled where supported, and schema acceptance is tested
  • The initial tool set is evaluated for selection accuracy and token cost, with deferral considered for large catalogs
  • An allowlist and validation layer sit between model output and function execution
  • Authorization checks cover the specific user, resource, and action
  • Credentials follow least privilege, and consequential actions require appropriate confirmation
  • Tool results are matched to their original call identifiers
  • Retry logic distinguishes transient failures from validation and permission errors
  • Side-effecting retries use idempotency protection where available
  • Parallel execution handles partial failures and ordering dependencies
  • Logging records call identifiers, validation outcomes, latency, and errors without unnecessary secrets or personal data
  • Tests cover ambiguous prompts, wrong-but-valid values, nested calls, unavailable tools, and exact production model configurations
  • Monitoring alerts on error rates, unexpected tool selection, and latency spikes

The difference between a prototype and a production system is not a single prompt or model release. It is the set of boundaries around the call: constrained generation, useful clarification behavior, validation, authorization, and recoverable execution. New APIs, deferred tool loading, and MCP can reduce integration work, but none removes the application’s responsibility for what a function is allowed to do.

References

Follow the links in the article for context. The supporting material is collected here for further reading.

  1. OpenAI. "Function Calling Guide."platform.openai.comAccessed
  2. Anthropic. "Building Effective Agents."anthropic.comAccessed
  3. Anthropic. "Tool Use Overview."docs.anthropic.comAccessed
  4. Anthropic. "Structured Outputs."docs.anthropic.comAccessed
  5. OpenAI. "Structured Outputs Guide."platform.openai.comAccessed
  6. Model Context Protocol. "Introduction to MCP."modelcontextprotocol.ioAccessed
  7. Anthropic. "Claude Opus 4.8."anthropic.comAccessed

Join the discussion

Share a useful perspective or ask a question about this article.

Discussion guidelinesComments privacy