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/:addandcount_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
#composer create-project taphra/skeleton my-app
cd my-appStep 2: Configure the provider
#Create app/Config/ai.yml:
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):
echo "ANTHROPIC_API_KEY=sk-ant-..." >> .envUse 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
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
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
// 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:
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:
...
tool: count_words {"text":"the quick brown fox"} -> {"words":4}
...
answer: ...
...How the loop works
#run()sends the question and the tool definitions to the model.- 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. - It sends the conversation back, and repeats until the model answers without asking for a tool.
maxIterations(5)caps the number of model calls in onerun(); past it,run()throwsTaphra\Ai\AiMaxIterationsException. Without the call, the cap isagent.max_iterationsinapp/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').
default_provider: openai
providers:
openai:
api_key: "${OPENAI_API_KEY}"
model: gpt-4o
ollama:
base_url: "http://localhost:11434"
model: llama3Next steps
#- Offer the same kind of tools to MCP clients such as desktop AI apps and IDEs: Tutorial 4: MCP server
- A streaming chat page: Tutorial 3: AI chatbot