Documentation menu

Tutorials

Tutorial 5: Agent with Tools

An agent is a model that can call your PHP code. You describe tools (a name, a description and a JSON Schema for the input); the model decides which to call, Taphra runs them and sends the results back, and the loop repeats until the model answers in plain text.

What you will build

#
  • two tools in app/AiTools/: add and count_words
  • a command line script that asks a question, prints each tool call and the final answer

Prerequisites

#
  • PHP 8.2 or later
  • Composer
  • An Anthropic API key (OpenAI and Ollama work too, see the end)

Step 1: Create the app

#
Shell
composer create-project taphra/skeleton my-app
cd my-app

Step 2: Configure the provider

#

Create app/Config/ai.yml:

YAML
default_provider: anthropic

providers:
  anthropic:
    api_key: "${ANTHROPIC_API_KEY}"
    model: claude-opus-5-5
    max_tokens: 4096

# Requests (messages included) are not written to app/tmp/Log/ai.log.
logging:
  enabled: false

${ANTHROPIC_API_KEY} is read from the environment. Put your key in .env, which app/bootstrap.php reads on every request and command (and which .gitignore keeps out of git):

Shell
echo "ANTHROPIC_API_KEY=sk-ant-..." >> .env

Use your real key in place of sk-ant-....

Step 3: The tools

#

A tool extends Taphra\Ai\AiTool and has four methods: name(), description() (the model reads it to decide when to call the tool), inputSchema() (JSON Schema for the arguments) and execute(), whose return value is sent to the model as JSON.

Create app/AiTools/AddTool.php:

PHP
<?php
namespace App\AiTools;

use Taphra\Ai\AiTool;

class AddTool extends AiTool
{
    public function name(): string
    {
        return 'add';
    }

    public function description(): string
    {
        return 'Adds two whole numbers.';
    }

    public function inputSchema(): array
    {
        return [
            'type'       => 'object',
            'properties' => [
                'a' => ['type' => 'integer'],
                'b' => ['type' => 'integer'],
            ],
            'required' => ['a', 'b'],
        ];
    }

    public function execute(array $params): array
    {
        return ['sum' => (int) $params['a'] + (int) $params['b']];
    }
}

Create app/AiTools/CountWordsTool.php:

PHP
<?php
namespace App\AiTools;

use Taphra\Ai\AiTool;

class CountWordsTool extends AiTool
{
    public function name(): string
    {
        return 'count_words';
    }

    public function description(): string
    {
        return 'Counts the words in a text.';
    }

    public function inputSchema(): array
    {
        return [
            'type'       => 'object',
            'properties' => [
                'text' => ['type' => 'string', 'description' => 'The text to count'],
            ],
            'required' => ['text'],
        ];
    }

    public function execute(array $params): array
    {
        return ['words' => str_word_count((string) $params['text'])];
    }
}

A tool that throws an exception does not stop the agent: the error goes back to the model as the tool's result, marked as an error.

Step 4: Run the agent

#

AI::agent() returns an AgentLoop on the default provider. Register the tools, optionally watch each call with onToolCall(), and run() a question. Create ask.php in the project folder:

PHP
<?php
// Usage: php ask.php "your question"

// Boots the framework and the app the way every entry point does.
require __DIR__ . '/app/Static/indexcommon.php';

use App\AiTools\AddTool;
use App\AiTools\CountWordsTool;
use Taphra\Ai\AI;

$question = $argv[1] ?? 'How many words are in "the quick brown fox"?';

$result = AI::agent()
    ->registerTool(new AddTool())
    ->registerTool(new CountWordsTool())
    ->maxIterations(5)
    ->onToolCall(function (string $name, array $params, string $result): void {
        echo "tool: $name ", json_encode($params), " -> $result\n";
    })
    ->run($question);

echo 'answer: ', $result['content'], "\n";

Ask it something a tool can answer:

Shell
php ask.php 'How many words are in "the quick brown fox"?'

The model's words vary from run to run; the tool's result does not. You see something like:

Text
...
tool: count_words {"text":"the quick brown fox"} -> {"words":4}
...
answer: ...
...

How the loop works

#
  1. run() sends the question and the tool definitions to the model.
  2. When the answer asks for tools (tool_use), the loop runs each one with the model's arguments and appends the results to the conversation.
  3. It sends the conversation back, and repeats until the model answers without asking for a tool.
  4. maxIterations(5) caps the number of model calls in one run(); past it, run() throws Taphra\Ai\AiMaxIterationsException. Without the call, the cap is agent.max_iterations in app/Config/ai.yml (default 10).

run() returns the final answer: $result['content'] is its text, $result['usage'] the tokens it used. The agent keeps the conversation, so a second run() on the same agent continues it; reset() starts over.

Each call of the loop is a paid request to the provider. Before you put an agent behind a web page, give that page a sign-in and a rate limit, as the taphra/ai-chat starter does.

Other providers

#

Set default_provider in app/Config/ai.yml to another entry, or pass a provider name: AI::agent('openai').

YAML
default_provider: openai

providers:
  openai:
    api_key: "${OPENAI_API_KEY}"
    model: gpt-4o
  ollama:
    base_url: "http://localhost:11434"
    model: llama3

Next steps

#