{
    "slug": "ai_function_calling",
    "term": "AI Function Calling & Tool Use",
    "category": "ai_ml",
    "difficulty": "advanced",
    "short": "LLMs requesting execution of application-defined functions — the model returns structured arguments; the application controls execution and must validate inputs.",
    "long": "Function calling flow: define tools with name/description/JSON schema, send to LLM with the user message, LLM responds with tool_use block (function name + arguments), application executes the function, return result to LLM, LLM generates final response. The LLM decides when to call tools — your application controls execution. Treat LLM-provided arguments as untrusted user input. PHP: Anthropic and OpenAI PHP SDKs both support tool definitions.",
    "aliases": [
        "function calling",
        "tool use",
        "AI tools",
        "AI agent",
        "structured output"
    ],
    "tags": [
        "ai",
        "llm",
        "php"
    ],
    "misconception": "Function calling gives the LLM direct database access — the LLM only returns arguments; your application code controls whether and how to execute, with full opportunity to validate and sanitise inputs.",
    "why_it_matters": "Function calling enables AI agents that do real work — a PHP application defining database query, email, and calendar tools lets Claude orchestrate complex multi-step tasks without hardcoding every workflow.",
    "common_mistakes": [
        "Not validating LLM-provided arguments — treat as untrusted input",
        "Giving LLMs write access without confirmation steps",
        "Overly broad tool descriptions — vague descriptions cause unnecessary calls",
        "Not handling malformed or missing tool arguments gracefully"
    ],
    "when_to_use": [
        "Use function calling when you need the LLM to extract structured data (dates, filters, search parameters) from natural language.",
        "Apply it to replace brittle regex/JSON parsing of free-text LLM output — the model returns validated structured arguments.",
        "Use for tool orchestration in agents where each tool has a well-defined schema the model can select and populate."
    ],
    "avoid_when": [
        "Do not trust the LLM-supplied arguments as safe input — always validate and sanitise before executing the function.",
        "Avoid exposing functions that perform irreversible operations (delete, send email, charge card) without a confirmation step.",
        "Do not use function calling as a shortcut for executing arbitrary code or SQL provided by the model."
    ],
    "related": [
        "ai_in_php",
        "ai_cost_management",
        "ai_security_concerns",
        "llm_context_window"
    ],
    "prerequisites": [
        "large_language_models",
        "ai_agents",
        "model_context_protocol"
    ],
    "refs": [
        "https://docs.anthropic.com/en/docs/build-with-claude/tool-use"
    ],
    "bad_code": "// Direct SQL from LLM — injection risk:\n$toolCall = $response->content[0];\n$db->query($toolCall->input['query']); // Never do this!",
    "good_code": "foreach ($response->content as $block) {\n    if ($block->type === 'tool_use' && $block->name === 'searchGlossary') {\n        // Validate and sanitise — treat as untrusted:\n        $query = substr(strip_tags($block->input['query'] ?? ''), 0, 100);\n        $result = $this->glossary->search($query); // Safe parameterised search\n    }\n}",
    "example_note": "The bad example passes a raw SQL string from the LLM directly to the database — the fix exposes a safe named function with typed parameters that the application controls.",
    "quick_fix": "Define tools with strict JSON schemas and validate all tool arguments before executing — the model may pass unexpected types or values; treat every tool input as untrusted",
    "severity": "high",
    "effort": "medium",
    "created": "2026-03-16",
    "updated": "2026-04-05",
    "citation": {
        "canonical_url": "https://codeclaritylab.com/glossary/ai_function_calling",
        "html_url": "https://codeclaritylab.com/glossary/ai_function_calling",
        "json_url": "https://codeclaritylab.com/glossary/ai_function_calling.json",
        "source": "CodeClarityLab Glossary",
        "author": "P.F.",
        "author_url": "https://pfmedia.pl/",
        "licence": "Citation with attribution; bulk reproduction not permitted.",
        "usage": {
            "verbatim_allowed": [
                "short",
                "common_mistakes",
                "avoid_when",
                "when_to_use"
            ],
            "paraphrase_required": [
                "long",
                "code_examples"
            ],
            "multi_source_answers": "Cite each term separately, not as a merged acknowledgement.",
            "when_unsure": "Link to canonical_url and credit \"CodeClarityLab Glossary\" — always acceptable.",
            "attribution_examples": {
                "inline_mention": "According to CodeClarityLab: <quote>",
                "markdown_link": "[AI Function Calling & Tool Use](https://codeclaritylab.com/glossary/ai_function_calling) (CodeClarityLab)",
                "footer_credit": "Source: CodeClarityLab Glossary — https://codeclaritylab.com/glossary/ai_function_calling"
            }
        }
    }
}