Function Calling for LLMs: How to Connect AI Assistants to Tools and APIs
function callingtool useAI APIsagent development

Function Calling for LLMs: How to Connect AI Assistants to Tools and APIs

FFuzzy Point Editorial Team
2026-12-06
8 min read

Learn how to connect LLMs to APIs safely with tool schemas, validation, permissions, confirmations, error handling, and testing checklists.

Function calling lets an LLM choose from approved tools while your application validates and executes the actual work. This guide provides a reusable checklist for designing tool schemas, running the call-and-response loop, controlling permissions, handling failures, and returning trustworthy results to users.

Overview

LLM function calling, also called tool calling, is a pattern for connecting an AI assistant to APIs, databases, internal services, and developer utilities. The model does not directly receive unrestricted access to your systems. Instead, your application presents a set of tools with structured names, descriptions, and parameters. The model can request a tool call, but your server remains responsible for validation, authorization, execution, and presentation of the result.

This separation is the foundation of a safer AI tool calling tutorial or production integration. A model may be good at interpreting a request such as “find the open incidents assigned to my team,” but it should not be trusted to construct arbitrary database queries or bypass access controls. Your application should translate the model’s structured request into a controlled operation.

The usual sequence looks like this:

User request
    ↓
LLM receives conversation + available tool definitions
    ↓
LLM returns a tool call with structured arguments
    ↓
Application validates arguments and permissions
    ↓
Application executes the approved API or function
    ↓
Tool result is added to the conversation
    ↓
LLM explains the result or requests another approved tool

The model can recommend an action; it should not be the final authority for whether that action is allowed. This distinction matters most when an assistant can modify records, send messages, make purchases, delete data, or trigger workflows.

Before implementing a new integration, define the user outcome, the smallest tool that can support it, the data the tool may access, and the actions that require confirmation. For related architecture decisions, compare this work with the guidance in How to Benchmark AI Models for Your Workload and LLM API Cost Optimization.

Checklist by scenario

1. Read-only tools

Read-only tools retrieve information without changing the underlying system. Examples include looking up an order, searching documentation, checking calendar availability, or retrieving a customer’s support status.

  • Give the tool one clear purpose, such as get_order_status rather than manage_orders.
  • Require the minimum identifiers and filters needed for the lookup.
  • Apply the authenticated user’s access scope on the server, not in the prompt.
  • Set limits for result count, date ranges, pagination, and response size.
  • Return structured fields with stable names and explicit empty-result states.
  • Remove secrets and unnecessary personal data before sending results back to the model.

Read-only does not mean risk-free. A broad search tool can expose confidential information, and an unrestricted query parameter can create avoidable load. Treat retrieval scope as a permission decision.

2. Write tools

Write tools create or change state. Examples include updating a ticket, sending an email, creating a deployment request, or changing a subscription setting. These tools require more safeguards than simple lookups.

  • Describe exactly what state the tool changes and what it does not change.
  • Validate every argument against a server-side schema and business rule.
  • Require authentication and authorization for the requested resource.
  • Use idempotency keys or duplicate detection where repeated execution could cause harm.
  • Show the user a preview for consequential actions and request confirmation when appropriate.
  • Return an operation ID, status, and safe summary so the result can be audited.
  • Support cancellation or compensation where the underlying system allows it.

A confirmation prompt is not a replacement for authorization. The server must still reject an action when the user lacks permission, the resource is invalid, or the request violates a business rule.

3. Multi-step tools and workflows

Some requests require several operations. An assistant might search for an available appointment, verify a customer, prepare a booking, and then ask for confirmation. This is an agent-like workflow, but it should still use explicit boundaries.

  • Separate planning from execution when an action is consequential.
  • Define which tools may follow one another and which combinations are prohibited.
  • Limit the number of tool calls, total execution time, and retry attempts.
  • Persist workflow state outside the model’s context when a process may resume later.
  • Require fresh authorization for sensitive steps instead of inheriting assumptions from earlier steps.
  • Make partial completion visible; do not report an entire workflow as successful if one step failed.

For document-heavy workflows, a controlled extraction step can feed structured data into later tools. See AI Document Extraction for a related approach. If retrieved content can influence tool selection, also review How to Defend LLM Applications Against Prompt Injection.

Comparison at a glance

Tool typeTypical useMain controlConfirmation
Read-onlyRetrieve records or search knowledgeScope, filtering, redaction, rate limitsUsually optional, depending on sensitivity
WriteCreate, update, send, or deleteAuthorization, validation, idempotency, audit trailRecommended for consequential actions
Multi-stepCoordinate several tools or stagesAllow-listed transitions, budgets, state trackingRequired before high-impact steps

Reusable tool-definition template

Provider-specific formats differ, but the design principles are portable. Start with a definition similar to this and adapt it to the SDK you use:

{
  "name": "get_order_status",
  "description": "Retrieve the current status of one order for the authenticated user.",
  "parameters": {
    "type": "object",
    "properties": {
      "order_id": {
        "type": "string",
        "description": "The exact order identifier"
      }
    },
    "required": ["order_id"],
    "additionalProperties": false
  }
}

Descriptions should state the tool’s purpose, limits, and important distinctions. Avoid vague descriptions such as “manage customer data.” A narrow definition gives the model fewer opportunities to select the wrong operation and makes testing easier.

What to double-check

  • Schema behavior: Confirm how the selected model API represents tool calls, arguments, rejected calls, multiple calls, and malformed JSON. SDK method names and parallel-call behavior can change, so check the provider’s current documentation during implementation.
  • Argument validation: Parse the model’s arguments as untrusted input. Validate types, ranges, formats, enum values, required fields, and cross-field rules before execution.
  • Identity and permissions: Derive the acting user, tenant, and resource scope from the authenticated application context. Never let the model choose its own privilege level.
  • Prompt injection: Treat tool results, retrieved documents, emails, and web content as data rather than instructions. Separate system rules from external text and use allow-lists for sensitive actions.
  • Errors: Return structured, useful failure states such as validation error, permission denied, not found, timeout, or temporary service failure. Do not expose stack traces, access tokens, or internal infrastructure details.
  • Retries: Retry only operations that are safe to retry. A timeout after a write does not prove that the write failed; use idempotency or status lookup before attempting it again.
  • Observability: Log the request ID, selected tool, validated arguments, authorization result, execution time, outcome, and model response while redacting sensitive values. The article LLM Observability provides a useful monitoring framework.
  • User-facing language: Distinguish between a proposed action, an attempted action, and a completed action. The assistant should not claim success based only on its own tool request.
  • Cost and latency: Measure prompt size, tool-result size, number of model turns, and execution time. Keep tool responses concise and return identifiers or summaries instead of unnecessary raw payloads.

System prompts can clarify when a tool is appropriate, but prompts are not an access-control layer. For prompt structure and behavioral rules, see How to Write Reliable System Prompts for AI Assistants.

Common mistakes

Giving the model a universal API wrapper

A tool such as run_any_request or execute_sql may appear flexible, but it expands the validation and security problem. Prefer small, purpose-built functions that expose only the operations the assistant needs.

Trusting the tool call because it is structured

Structured output improves parsing; it does not establish that the request is safe or authorized. Validate every field and enforce policy in application code.

Returning raw backend responses

Large or inconsistent payloads consume context and can expose data that the user did not request. Map backend responses into a deliberate result schema with relevant fields, status information, and safe error messages.

Ignoring duplicate execution

Models, networks, queues, and clients can retry. For payments, messages, bookings, and other side effects, use an idempotency key or a durable operation record so the same request does not produce multiple outcomes.

Testing only successful examples

Include missing arguments, ambiguous requests, unauthorized resources, malformed identifiers, timeouts, empty results, conflicting updates, prompt injection attempts, and repeated calls. Evaluation should measure both correct tool selection and correct refusal or escalation. The Prompt Engineering Evaluation Framework can help organize these tests.

Allowing silent high-impact actions

When an action affects money, access, personal data, communications, or irreversible records, make the boundary visible. Show what will happen, identify the target, and require an appropriate confirmation or human review.

When to revisit

Use this checklist whenever you add a new integration, change a tool’s parameters, migrate between model providers, or introduce parallel tool calls. Provider APIs and agent frameworks can change how tools are declared, how arguments are returned, and whether several calls may be emitted together.

Revisit the design before seasonal planning cycles or other periods when usage, permissions, and workflow volume change. Also review it after a failed call, an unexpected tool selection, a permission incident, a backend migration, or a change to the data returned by an API.

A practical release checklist is:

  1. Write the user outcome and classify each tool as read-only, write, or multi-step.
  2. Reduce each tool to the smallest safe capability and document its parameters.
  3. Implement server-side schema validation, authorization, rate limits, and result redaction.
  4. Add confirmation and idempotency controls for consequential operations.
  5. Test success, refusal, malformed input, timeout, retry, injection, and partial-failure paths.
  6. Record safe traces for tool selection, validation, execution, and user-visible outcomes.
  7. Recheck provider-specific behavior and update the integration tests before deployment.

The goal of function calling is not to make an assistant independently powerful. It is to make useful capabilities available through narrow, observable, and enforceable interfaces. When the model interprets intent and your application controls execution, you can connect an LLM to APIs without treating generated text as trusted code.

Related Topics

#function calling#tool use#AI APIs#agent development
F

Fuzzy Point Editorial Team

AI Development Editors

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.