{
    "slug": "ai_agent_pattern",
    "term": "AI Agent Pattern",
    "category": "ai_ml",
    "difficulty": "advanced",
    "short": "An LLM-powered system that takes multi-step actions autonomously — calling tools, reading results, and deciding next steps in a loop until a goal is achieved.",
    "long": "An AI agent extends a simple LLM call by giving the model access to tools — functions it can invoke to take actions in the world. The agent receives a goal, reasons about what tool to call, receives the tool result, and repeats until it can produce a final answer. Common tools include web search, code execution, database queries, and API calls. The ReAct pattern (Reasoning + Acting) is the most common agent architecture: the model alternates between Thought (reasoning about what to do), Action (calling a tool), and Observation (receiving the result). In PHP, agents are typically built by calling an LLM API in a loop, parsing tool-call responses, executing the requested function, and feeding results back as the next message.",
    "aliases": [
        "LLM agent",
        "autonomous agent",
        "ReAct agent",
        "tool-using LLM",
        "agentic AI"
    ],
    "tags": [
        "ai-agent",
        "llm",
        "tools",
        "autonomous",
        "react-pattern"
    ],
    "misconception": "AI agents are reliable enough to run autonomously without human oversight. Current LLM agents have high failure rates on complex multi-step tasks, accumulate errors across steps, and can take irreversible actions (deleting files, sending emails, making API calls) based on misunderstandings. Always implement human-in-the-loop checkpoints for consequential actions, add hard limits on loop iterations, and log every tool call.",
    "why_it_matters": "The agent pattern is how LLMs become useful for tasks that require multiple steps, external data, or real-world actions — beyond single-turn Q&A. A PHP application that answers 'what is our revenue this quarter' by calling a database tool, running a calculation tool, and formatting the result is an agent. Understanding the pattern is essential for building LLM features that are more capable than a simple chat interface, while understanding the failure modes is essential for building them safely.",
    "common_mistakes": [
        "No iteration limit — agents can loop indefinitely if the model repeatedly calls the wrong tool or misinterprets results.",
        "Giving the agent access to destructive tools without confirmation — file deletion, email sending, and database writes should require explicit user approval.",
        "Not logging tool calls — debugging an agent that produced a wrong answer requires replaying every reasoning step.",
        "Treating the agent as deterministic — the same input may take different tool-calling paths across runs, making testing difficult."
    ],
    "when_to_use": [
        "Multi-step tasks that require planning, tool use, and adapting based on intermediate results.",
        "Workflows where the path to the answer is not known upfront and the model must discover it.",
        "Automating research, code review, or data gathering tasks that a human would do step-by-step.",
        "When tool-use (web search, code execution, DB queries) is required to answer the goal."
    ],
    "avoid_when": [
        "Simple single-turn tasks where a standard LLM call is sufficient — agents add latency and cost per loop iteration.",
        "Irreversible actions without human confirmation — agents can take destructive actions based on misunderstood goals.",
        "Untrusted or ambiguous goals — an agent given a vague objective may pursue an unintended interpretation.",
        "Production environments without iteration limits and logging — runaway agents consume tokens and cause unintended side effects."
    ],
    "related": [
        "hallucination",
        "prompt_engineering",
        "chain_of_thought",
        "rag_retrieval"
    ],
    "prerequisites": [],
    "refs": [
        "https://arxiv.org/abs/2210.03629"
    ],
    "bad_code": "// ❌ No iteration limit, no logging, destructive tool access\nfunction runAgent(string $goal): string {\n    while (true) {\n        $response = callLLM($goal);\n        if ($response['done']) return $response['answer'];\n        $result = executeTool($response['tool'], $response['args']); // may delete files!\n        $goal .= $result;\n    }\n    // infinite loop possible, no audit trail\n}",
    "good_code": "<?php\n// ✅ Agent with iteration limit, logging, and confirmation for destructive actions\nfunction runAgent(string $goal, array $tools, int $maxIterations = 10): string\n{\n    $messages = [['role' => 'user', 'content' => $goal]];\n    $iteration = 0;\n\n    while ($iteration < $maxIterations) {\n        $response = callLLM($messages, $tools);\n        Log::info('Agent step', ['iteration' => $iteration, 'response' => $response]);\n\n        if ($response['done']) return $response['answer'];\n\n        // Require confirmation before destructive tools\n        if (isDestructive($response['tool'])) {\n            confirmWithUser($response['tool'], $response['args']);\n        }\n\n        $result = executeTool($response['tool'], $response['args']);\n        $messages[] = ['role' => 'tool', 'content' => $result];\n        $iteration++;\n    }\n\n    throw new RuntimeException(\"Agent exceeded max iterations ($maxIterations)\");\n}",
    "quick_fix": "Always set a max_iterations limit (10 is reasonable), log every tool call with inputs and outputs, and require confirmation before any irreversible action",
    "severity": "high",
    "effort": "high",
    "created": "2026-03-23",
    "updated": "2026-03-25",
    "citation": {
        "canonical_url": "https://codeclaritylab.com/glossary/ai_agent_pattern",
        "html_url": "https://codeclaritylab.com/glossary/ai_agent_pattern",
        "json_url": "https://codeclaritylab.com/glossary/ai_agent_pattern.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 Agent Pattern](https://codeclaritylab.com/glossary/ai_agent_pattern) (CodeClarityLab)",
                "footer_credit": "Source: CodeClarityLab Glossary — https://codeclaritylab.com/glossary/ai_agent_pattern"
            }
        }
    }
}