Function Calling Done Right: Patterns for Reliable Tool Use
Back to all articles
AI Engineering
17 min read7 min read

Function Calling Done Right: Patterns for Reliable Tool Use

How to build reliable function calling systems. Covers tool definition, error handling, validation, and multi-tool orchestration.

Debasish Maji
Debasish Maji
AI Engineering Lead
April 7, 2026
Function CallingTool UseAgentsReliability

The Promise and Reality of Function Calling

Function calling lets LLMs interact with external systems - databases, APIs, file systems. In theory, you define functions, the model calls them, magic happens.

In practice, models hallucinate function names, pass invalid arguments, call functions in the wrong order, and confidently return made-up results.

This post documents the patterns we use to achieve 98% tool call accuracy in production.

•••

The Failure Modes

Before solutions, understand the problems:

Failure ModeFrequencyExample
Invalid arguments34%String where number expected
Hallucinated functions18%Calls tool that does not exist
Wrong function choice22%Uses search when should use lookup
Missing required args15%Omits required parameter
Type coercion errors11%"123" instead of 123
These were our error rates before implementing the patterns below.

•••

Pattern 1: Schema-First Tool Definition

Do not let the model guess. Define explicit schemas.

Tool Schema Structure

Every tool needs:

FieldPurposeExample
nameUnique identifierget_customer_orders
descriptionWhat it does (for LLM)Retrieves order history for a customer
parametersJSON SchemaSee below
requiredMandatory params["customer_id"]
examplesUsage examplesInput/output pairs

Description Best Practices

Good descriptions dramatically improve accuracy:

BadGood
"Gets orders""Retrieves the complete order history for a specific customer, including order IDs, dates, items, and totals"
"Search""Searches the product catalog by keyword. Returns up to 10 matching products with names, prices, and availability"
Include what it returns, not just what it does.

Parameter Descriptions

Every parameter needs a description:

Without DescriptionWith Description
76% accuracy94% accuracy
The model needs context to choose correct values.

•••

Pattern 2: Validation Layer

Never trust model output. Always validate.

Validation Pipeline

Every tool call goes through validation:

StepWhat It ChecksAction on Failure
Schema validationTypes match schemaReturn error to model
Business rulesValues make senseReturn error with guidance
AuthorizationUser can do thisBlock and log
Rate limitingNot too many callsQueue or reject

Validation Results

Validation TypeCatchesRecovery Rate
Schema89% of type errors96%
Business rules78% of logic errors84%
Combined94% of all errors91%
Most invalid calls can be recovered with good error messages.

•••

Pattern 3: Error Messages That Help

When validation fails, tell the model how to fix it:

Bad ErrorGood Error
"Invalid input""customer_id must be a positive integer, received: abc"
"Failed""search_products requires at least one of: keyword, category, or price_range"
"Type error""quantity must be a number between 1 and 100, received: 150"
Good error messages include what was wrong, what was expected, and what was received.

Error Message Impact

Error QualityRetry Success Rate
Generic34%
Specific78%
With examples91%
•••

Pattern 4: Tool Selection Guidance

Help the model choose the right tool.

When Multiple Tools Could Apply

For overlapping functionality, add selection hints:

ScenarioToolWhen to Use
Find specific orderget_orderHave order_id
Find customer ordersget_customer_ordersHave customer_id, want all orders
Search orderssearch_ordersHave search criteria, no IDs
Include this guidance in the system prompt or tool descriptions.

Disambiguation Examples

Add examples that show when to use each tool:

User QueryCorrect ToolWhy
"What is order 12345?"get_orderSpecific order ID
"Show my recent orders"get_customer_ordersCustomer context, no order ID
"Find orders over $100"search_ordersSearch criteria
•••

Pattern 5: Structured Output Enforcement

Use structured output modes when available:

JSON Mode Benefits

Without JSON ModeWith JSON Mode
82% valid JSON99.7% valid JSON
Manual parsingGuaranteed structure
Format driftConsistent format

Constrained Output

When the model should only call tools (not respond directly):

Force tool use when appropriate. This prevents the model from making up answers when it should use tools.

•••

Pattern 6: Multi-Step Tool Orchestration

Complex tasks require multiple tool calls.

Orchestration Patterns

PatternUse CaseExample
SequentialDependent stepsGet customer, then get orders
ParallelIndependent stepsGet orders AND get preferences
ConditionalBased on resultIf order exists, get details
IterativeRepeat until donePage through results

Sequential Execution

When steps depend on each other:

StepToolDepends On
1get_customerNone
2get_customer_ordersStep 1 result
3calculate_totalStep 2 result
Pass previous results to subsequent calls.

Parallel Execution

When steps are independent, run them together to reduce latency:

SequentialParallel
3.2s total1.1s total
Parallel execution can 3x faster for independent operations.

•••

Pattern 7: Graceful Degradation

When tools fail, handle gracefully.

Fallback Strategy

Primary FailsFallback Action
Database timeoutUse cached data
API rate limitedQueue and retry
Service downExplain limitation
Invalid dataAsk for clarification

User Communication

When tools cannot complete:

BadGood
"Error occurred""I could not retrieve your orders because the order system is currently slow. Would you like me to try again in a moment?"
Be specific about what failed and offer alternatives.

•••

Pattern 8: Observability

Track everything about tool usage.

Metrics to Track

MetricPurposeAlert Threshold
Call success rateOverall healthLess than 95%
Avg latencyPerformanceMore than 2s
Error by typeDebug issuesAny spike
Retry rateModel strugglingMore than 10%
Tool usage distributionUnderstand patternsAnomalies

Logging Tool Calls

Every tool call should log:

FieldPurpose
request_idCorrelation
tool_nameWhat was called
argumentsWhat was passed
validation_resultDid it validate
execution_timeHow long
result_summaryWhat happened
errorIf failed, why
•••

Production Results

After implementing all patterns:

MetricBeforeAfter
Tool call accuracy71%98%
First-attempt success58%89%
Avg retries needed1.80.3
User task completion64%94%
Support escalations23%4%
•••

Key Takeaways

  1. 1Schemas are documentation for models - Detailed descriptions and examples dramatically improve accuracy.
  1. 2Validate everything - Never trust model output. Schema validation catches most errors.
  1. 3Helpful errors enable recovery - Good error messages let the model self-correct.
  1. 4Guide tool selection - When tools overlap, add explicit guidance on when to use each.
  1. 5Structured output is worth it - JSON mode and constrained generation eliminate entire error classes.
  1. 6Observe and iterate - Track tool usage patterns to find and fix systematic issues.

Function calling turns LLMs from chat interfaces into capable assistants. But reliability requires deliberate engineering - the patterns above are how we get there.

Found this helpful?

Share it with others who might benefit

TweetShare

Related articles