Agentic AIPHPverifiedVerified

Tool Use Agent Pattern in PHP

Augment an LLM with callable external tools — APIs, code interpreters, databases — so it can take actions and retrieve real-time information beyond its training data.

How to Implement the Tool Use Agent Pattern in PHP

1Step 1: Define tool schema and registry

class ToolSchema
{
    public function __construct(
        public readonly string $name,
        public readonly string $description,
        /** @var array<string, string> */
        public readonly array $parameters,
    ) {}
}

interface ToolExecutor
{
    public function execute(string $name, array $args): string;
}

2Step 2: Implement a simple tool registry

class ToolRegistry implements ToolExecutor
{
    /** @var array<string, callable> */
    private array $handlers = [];
    /** @var ToolSchema[] */
    private array $schemas = [];

    public function register(ToolSchema $schema, callable $handler): void
    {
        $this->schemas[$schema->name] = $schema;
        $this->handlers[$schema->name] = $handler;
    }

    public function execute(string $name, array $args): string
    {
        if (!isset($this->handlers[$name])) {
            throw new \RuntimeException("Tool not found: {$name}");
        }
        return ($this->handlers[$name])($args);
    }

    /** @return ToolSchema[] */
    public function getSchemas(): array
    {
        return array_values($this->schemas);
    }
}

3Step 3: Wire tools to an LLM interaction loop

function toolUseLoop(string $query, ToolRegistry $registry, callable $llm): string
{
    $schemas = $registry->getSchemas();
    $prompt = "Query: {$query}\nAvailable tools: " .
        implode(', ', array_map(fn(ToolSchema $s) => $s->name, $schemas));

    $response = $llm($prompt);
    $parsed = json_decode($response, true);

    if (isset($parsed['tool'])) {
        $result = $registry->execute($parsed['tool'], $parsed['args'] ?? []);
        return $llm("Tool result: {$result}\nProvide final answer.");
    }

    return $response;
}

Tool Use Agent Pattern Architecture

hourglass_empty

Rendering diagram...

lightbulb

Tool Use Agent Pattern in the Real World

A lawyer (the LLM) in a courtroom knows the law but needs a paralegal team (the tools) to pull case files, run searches, and retrieve exhibits. The lawyer directs which file to fetch, the paralegal returns it, and the lawyer integrates that information into their argument — the lawyer's intelligence is amplified by the support staff's ability to reach into the real world.