Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/phpaisdk/core/llms.txt

Use this file to discover all available pages before exploring further.

Tool is the core abstraction for giving AI models access to PHP callables. A tool carries a name, a description shown to the model, an input schema describing the arguments, and a handler invoked when the model calls the tool. It can be defined inline with the fluent builder API or as a dedicated class that extends Tool and implements __invoke.

Tool::make()

Create or resolve a tool. Accepts an inline name string, an existing Tool instance (returned as-is), or a class name that will be resolved via the SDK container.
public static function make(string|object $tool, string $description = ''): self
tool
string | object
required
One of:
  • A plain string tool name (e.g. 'get_weather') — creates an inline tool.
  • A fully-qualified class name string — instantiates the class (optionally via the container) and returns it as a Tool.
  • An existing Tool instance — returned unchanged.
description
string
default:"''"
Human-readable description shown to the model. Only used when creating an inline tool from a name string.
// Inline tool
$tool = Tool::make('get_weather', 'Fetch current weather for a city')
    ->input(Schema::string('location', 'City name')->required())
    ->run(fn(string $location) => "Sunny in {$location}");

// Class-based tool
$tool = Tool::make(WeatherTool::class);

Instance methods

named()

Set or update the tool’s name. Also callable as ->as(string $name).
public function named(string $name): self
name
string
required
The tool name passed to the model. Must be unique across all tools registered on a request.
$tool = Tool::make('', 'Look up exchange rates')
    ->named('get_exchange_rate');

// Equivalent using the magic alias:
$tool = Tool::make('', 'Look up exchange rates')
    ->as('get_exchange_rate');

for()

Set or update the tool’s description.
public function for(string $description): self
description
string
required
A clear, model-facing description of what the tool does and when to use it.
$tool = Tool::make('search')
    ->for('Search the web and return the top 5 results for a query.');

input()

Define the tool’s input using a single schema. For primitive inputs the schema must be named; for an object schema the schema’s own properties become the parameters.
public function input(Schema $schema): self
schema
Schema
required
A named Schema instance describing the input. If the schema type is not object, it must have a non-empty name. Replaces any previously registered inputs.
// Single string parameter
$tool = Tool::make('translate', 'Translate text to Spanish')
    ->input(Schema::string('text', 'Text to translate')->required())
    ->run(fn(string $text) => translateToSpanish($text));

// Object parameter (nested properties)
$tool = Tool::make('create_event', 'Create a calendar event')
    ->input(
        Schema::object('event', properties: [
            Schema::string('title')->required(),
            Schema::string('date', 'ISO 8601 date')->required(),
        ])
    )
    ->run(fn(array $event) => createCalendarEvent($event));

inputs()

Define the tool’s input as multiple named schemas. Each schema maps to a positional argument in the handler.
public function inputs(array $schemas): self
schemas
Schema[]
required
A non-empty indexed array of named Schema instances. Every schema must have a non-empty name. Throws InvalidArgumentException when the array is empty or contains unnamed schemas.
$tool = Tool::make('convert_currency', 'Convert an amount between currencies')
    ->inputs([
        Schema::number('amount', 'Amount to convert')->required(),
        Schema::string('from', 'Source currency code, e.g. USD')->required(),
        Schema::string('to', 'Target currency code, e.g. EUR')->required(),
    ])
    ->run(fn(float $amount, string $from, string $to) => convert($amount, $from, $to));

run()

Attach the callable handler that is invoked when the model calls this tool.
public function run(callable $handler): self
handler
callable
required
A callable that receives the validated input arguments as positional parameters. Optionally receives a ToolExecutionContext as a final argument when the handler signature declares it.
$tool = Tool::make('add', 'Add two numbers')
    ->inputs([
        Schema::number('a')->required(),
        Schema::number('b')->required(),
    ])
    ->run(fn(float $a, float $b) => $a + $b);

name()

Return the tool’s current name.
public function name(): string
return
string
The tool name. Empty string if none has been set.
$tool = Tool::make('search', 'Web search');
echo $tool->name(); // "search"

description()

Return the tool’s description string.
public function description(): string
return
string
The description shown to the model.
echo $tool->description(); // "Web search"

handler()

Return the registered callable handler, or null if no handler has been attached. For class-based tools, returns $this when the class implements __invoke.
public function handler(): ?callable
return
callable | null
The tool handler, or null when none has been set and the object does not implement __invoke.
$handler = $tool->handler();
if ($handler !== null) {
    $result = $handler('London');
}

inputSchemaForProvider()

Return the tool’s input as a JSON Schema array in the format expected by AI providers.
public function inputSchemaForProvider(): array
return
array<string, mixed>
A JSON Schema object. Returns {"type":"object","properties":{}} when no inputs are defined. For a single object schema, returns that schema’s jsonSchema() directly. For multiple named schemas, they are wrapped in a synthesised object.
print_r($tool->inputSchemaForProvider());
/*
[
  'type'       => 'object',
  'properties' => [
    'location' => ['type' => 'string', 'description' => 'City name'],
  ],
  'required'   => ['location'],
  'additionalProperties' => false,
]
*/

call()

Validate the arguments and invoke the handler. Throws ToolExecutionException on handler failure and InvalidToolInputException on validation errors.
public function call(array $args, ?ToolExecutionContext $context = null): mixed
args
array<string, mixed>
required
The raw arguments object supplied by the model, keyed by parameter name.
context
ToolExecutionContext | null
default:"null"
Optional execution context. Automatically forwarded to the handler if the handler’s signature declares a final ToolExecutionContext parameter.
return
mixed
The value returned by the handler. Serialized to a string by the calling loop when appended to the conversation.
$result = $tool->call(['location' => 'Berlin']);
echo $result; // "Sunny in Berlin"

ToolChoice

ToolChoice is a value object that instructs the model how to select tools during generation.

Constants

ConstantValueMeaning
ToolChoice::AUTO'auto'Model decides whether to call a tool
ToolChoice::NONE'none'Tools are registered but the model must not call any
ToolChoice::REQUIRED'required'Model must call at least one tool
ToolChoice::TOOL'tool'Model must call the named tool

Static factory methods

public static function auto(): self
public static function none(): self
public static function required(): self
public static function tool(string $toolName): self
public static function from(string|self $choice): self
toolName
string
Required only for ToolChoice::tool(). The exact name of the tool the model must call. Throws InvalidArgumentException when empty.
ToolChoice::from() is a convenience normaliser — pass a ToolChoice instance (returned as-is) or one of the string constants 'auto', 'none', or 'required'. Any other string is treated as a tool name and delegates to ToolChoice::tool().
public static function from(string|self $choice): self
choice
string | ToolChoice
required
A ToolChoice instance or one of the string values 'auto', 'none', 'required', or a tool name string.
// Let the model decide
Generate::text()->toolChoice(ToolChoice::auto());

// Force the model to call a specific tool
Generate::text()->toolChoice(ToolChoice::tool('get_weather'));

// Prevent tool calls entirely
Generate::text()->toolChoice(ToolChoice::none());

// String shorthand resolved via ToolChoice::from()
Generate::text()->toolChoice('required');
Generate::text()->toolChoice('get_weather');

ToolExecutionContext

ToolExecutionContext is a read-only value object injected into tool handlers that declare it as their final parameter. It provides runtime context about the current tool call.
final class ToolExecutionContext
{
    public function __construct(
        public readonly string $toolCallId,
        public readonly string $toolName,
        public readonly array  $arguments,
        public readonly array  $messages = [],
    ) {}
}
toolCallId
string
The unique identifier for this specific tool call, assigned by the model.
toolName
string
The name of the tool being called.
arguments
array<string, mixed>
The raw argument map as supplied by the model before validation.
messages
Message[]
The full conversation message history at the time of tool invocation, including all prior assistant and tool messages in the current step loop.
$tool = Tool::make('summarise_history', 'Summarise the conversation so far')
    ->run(function (ToolExecutionContext $ctx) {
        $count = count($ctx->messages);
        return "Summarising {$count} messages for call {$ctx->toolCallId}.";
    });

ToolPackageInterface

Implement ToolPackageInterface to group related tools into a single registerable package.
interface ToolPackageInterface
{
    public function tools(): iterable;
}
tools()
iterable
Returns any iterable of tools (arrays, generators, or collections). Each item is resolved via ToolResolver, so class names, Tool instances, and invokable objects are all accepted.
class WeatherToolPackage implements ToolPackageInterface
{
    public function tools(): iterable
    {
        yield Tool::make('get_weather', 'Get current conditions')
            ->input(Schema::string('city')->required())
            ->run(fn(string $city) => fetchWeather($city));

        yield Tool::make('get_forecast', 'Get 5-day forecast')
            ->input(Schema::string('city')->required())
            ->run(fn(string $city) => fetchForecast($city));
    }
}

Generate::text()
    ->prompt('What is the weather and forecast for Tokyo?')
    ->tools(new WeatherToolPackage())
    ->maxSteps(3)
    ->run();

Class-based tool example

Extend Tool directly to create a self-contained, reusable tool class. Implement __invoke as the handler — the SDK detects it automatically.
class SearchTool extends Tool
{
    public function __construct()
    {
        parent::__construct(
            name: 'web_search',
            description: 'Search the web and return the top results.',
            input: Schema::object('params', properties: [
                Schema::string('query', 'The search query')->required(),
                Schema::integer('limit', 'Number of results to return'),
            ]),
        );
    }

    public function __invoke(array $params, ToolExecutionContext $context): array
    {
        $query = $params['query'];
        $limit = $params['limit'] ?? 5;

        // perform search...
        return array_slice(search($query), 0, $limit);
    }
}

// Register by class name — the SDK resolves and instantiates it
Generate::text()
    ->prompt('Find recent news about PHP 8.4')
    ->tool(SearchTool::class)
    ->maxSteps(3)
    ->run();

Build docs developers (and LLMs) love