Search by

adachsoft / ai-tool-call

Arkadiusz Adach

Unified AI tool-calling abstraction for PHP 8.3 with a clean Public API and an extensible SPI for custom tools.

Package info

gitlab.com/a.adach/AiToolCall

Issues

pkg:composer/adachsoft/ai-tool-call

Statistics

Installs: 494

Dependents: 41

Suggesters: 0

Stars: 0

v2.3.0 2026-11-20 05:15 UTC

This package is auto-updated.

Last update: 2026-11-20 04:15:25 UTC


README

Unified AI tool-calling abstraction for PHP 8.3 with a clean Public API and an extensible SPI for custom tools.

  • Public API to list and call tools via a simple facade.
  • SPI to implement your own tools (factories) in a framework-agnostic way.
  • Zero framework assumptions, manual wiring via a small Builder.
  • Uses adachsoft/collection for strict, immutable collections.

Requirements

  • PHP ^8.3
  • adachsoft/collection ^3.0

Installation

composer require adachsoft/ai-tool-call

Quick Start (SPI with factories)

use AdachSoft\AiToolCall\PublicApi\Builder\AiToolCallFacadeBuilder;
use AdachSoft\AiToolCall\PublicApi\Dto\ToolCallRequestDto;
use AdachSoft\AiToolCall\SPI\Collection\ConfigMap;
use AdachSoft\AiToolCall\SPI\Collection\KeyValueMap;
use AdachSoft\AiToolCall\SPI\Collection\TagsCollection;
use AdachSoft\AiToolCall\SPI\Dto\ToolCallRequestDto as SpiRequestDto;
use AdachSoft\AiToolCall\SPI\Dto\ToolCallResultDto as SpiResultDto;
use AdachSoft\AiToolCall\SPI\Dto\ToolDefinitionDto;
use AdachSoft\AiToolCall\SPI\Exception\ToolConfigurationException;
use AdachSoft\AiToolCall\SPI\Factory\ToolFactoryInterface;
use AdachSoft\AiToolCall\SPI\ToolInterface;

final class EchoTool implements ToolInterface
{
    public static function getDefinition(): ToolDefinitionDto
    {
        return new ToolDefinitionDto(
            name: 'echo',
            description: 'Returns input as output',
            parametersSchema: [
                'type' => 'object',
                'properties' => [
                    'text' => ['type' => 'string'],
                ],
            ],
            tags: new TagsCollection(['demo']),
            enabled: true,
        );
    }

    public function callTool(SpiRequestDto $request): SpiResultDto
    {
        return new SpiResultDto(
            'echo',
            new KeyValueMap(['text' => $request->parameters->get('text')])
        );
    }
}

final class EchoToolFactory implements ToolFactoryInterface
{
    public function getToolClass(): string
    {
        return EchoTool::class;
    }

    public function create(ConfigMap $config): ToolInterface
    {
        if ($config->has('invalid')) {
            throw new ToolConfigurationException('Invalid configuration for EchoTool.');
        }

        return new EchoTool();
    }
}

$facade = AiToolCallFacadeBuilder::new()
    ->withSpiFactories([new EchoToolFactory()])
    ->withToolConfigs([
        'echo' => new ConfigMap([]),
    ])
    ->build();

// List available tools (includes built-in current_datetime and your SPI tools)
$tools = $facade->listAvailableTools();
foreach ($tools as $tool) {
    echo $tool->name . PHP_EOL;
}

// Call a SPI tool
$result = $facade->callTool(new ToolCallRequestDto(
    toolName: 'echo',
    parameters: ['text' => 'hello'],
));

var_dump($result->result);

// Call the built-in current_datetime tool
$currentDateTimeResult = $facade->callTool(new ToolCallRequestDto(
    toolName: 'current_datetime',
    parameters: [],
));

var_dump($currentDateTimeResult->result);

Public API

  • Facade: AdachSoft\AiToolCall\PublicApi\AiToolCallFacadeInterface
    • callTool(ToolCallRequestDto): ToolCallResultDto
    • listAvailableTools(): AvailableToolCollection
    • listAvailableToolsByTags(array $tags): AvailableToolCollection

DTOs

  • ToolCallRequestDto(string $toolName, array $parameters)
  • ToolCallResultDto(string $toolName, mixed $result, ToolMediaCollection $media = new ToolMediaCollection())
  • ToolMediaDto(string $mimeType, string $base64Data, ?string $filename = null)
  • ToolMediaCollection
  • AvailableToolDto(string $name, string $description, array $parametersSchema, array $tags)
  • AvailableToolCollection

SPI (Service Provider Interface)

Implement custom tools by fulfilling the SPI contracts.

  • AdachSoft\AiToolCall\SPI\ToolInterface

    • callTool(ToolCallRequestDto): ToolCallResultDto
    • static getDefinition(): ToolDefinitionDto
  • AdachSoft\AiToolCall\SPI\DynamicToolInterface

    • callTool(ToolCallRequestDto): ToolCallResultDto
    • getDefinition(): ToolDefinitionDto for the configured instance
  • AdachSoft\AiToolCall\SPI\Factory\ToolFactoryInterface

    • getToolClass(): string
    • create(ConfigMap $config): ToolInterface
  • AdachSoft\AiToolCall\SPI\Factory\DynamicToolFactoryInterface

    • getToolName(): string
    • getToolDescription(): string
    • create(ConfigMap $config): DynamicToolInterface
  • ToolDefinitionDto

    • name: string
    • description: string
    • parametersSchema: array<string, mixed>
    • tags: TagsCollection
    • enabled: bool
  • Collections used in SPI:

    • TagsCollection (immutable list of strings)
    • KeyValueMap (immutable map string->mixed)
    • ConfigMap (immutable map string->mixed)
    • ToolMediaCollection (immutable collection of media returned by SPI tools)
    • ToolCollection (immutable collection of SPI tools)
    • DynamicToolCollection (immutable collection of dynamic SPI tools)
    • ToolFactoryCollection (immutable collection of SPI tool factories)

Minimal tool example (SPI-only)

use AdachSoft\AiToolCall\SPI\ToolInterface;
use AdachSoft\AiToolCall\SPI\Collection\ToolCollection as SpiToolCollection;
use AdachSoft\AiToolCall\SPI\Dto\ToolDefinitionDto;
use AdachSoft\AiToolCall\SPI\Dto\ToolCallRequestDto as SpiRequest;
use AdachSoft\AiToolCall\SPI\Dto\ToolCallResultDto as SpiResult;
use AdachSoft\AiToolCall\SPI\Collection\TagsCollection;
use AdachSoft\AiToolCall\SPI\Collection\KeyValueMap;

final class EchoTool implements ToolInterface
{
    public static function getDefinition(): ToolDefinitionDto
    {
        return new ToolDefinitionDto(
            name: 'echo',
            description: 'Returns input as output',
            parametersSchema: ['type' => 'object', 'properties' => ['text' => ['type' => 'string']]],
            tags: new TagsCollection(['demo']),
            enabled: true,
        );
    }

    public function callTool(SpiRequest $request): SpiResult
    {
        return new SpiResult('echo', new KeyValueMap(['text' => $request->parameters->get('text')]));
    }
}

$tools = new SpiToolCollection([new EchoTool()]);

Dynamic tools

Use dynamic tools when a tool's parameter schema depends on its configured instance, such as an enum loaded from dependency injection or runtime configuration. Keep using ToolInterface and ToolFactoryInterface when the definition is static.

A dynamic tool returns its definition from getDefinition(). Its factory exposes the tool name and description and creates the configured instance:

use AdachSoft\AiToolCall\PublicApi\Builder\AiToolCallFacadeBuilder;
use AdachSoft\AiToolCall\SPI\Collection\ConfigMap;
use AdachSoft\AiToolCall\SPI\Collection\DynamicToolCollection;
use AdachSoft\AiToolCall\SPI\Collection\KeyValueMap;
use AdachSoft\AiToolCall\SPI\Collection\TagsCollection;
use AdachSoft\AiToolCall\SPI\Dto\ToolCallRequestDto as SpiRequest;
use AdachSoft\AiToolCall\SPI\Dto\ToolCallResultDto as SpiResult;
use AdachSoft\AiToolCall\SPI\Dto\ToolDefinitionDto;
use AdachSoft\AiToolCall\SPI\DynamicToolInterface;
use AdachSoft\AiToolCall\SPI\Exception\ToolConfigurationException;
use AdachSoft\AiToolCall\SPI\Factory\DynamicToolFactoryInterface;

final class CategoryTool implements DynamicToolInterface
{
    public function __construct(private readonly string $category)
    {
    }

    public function callTool(SpiRequest $request): SpiResult
    {
        return new SpiResult(
            toolName: 'category_lookup',
            result: new KeyValueMap(['category' => $request->parameters->get('category')]),
        );
    }

    public function getDefinition(): ToolDefinitionDto
    {
        return new ToolDefinitionDto(
            name: 'category_lookup',
            description: 'Looks up items in the configured category',
            parametersSchema: [
                'type' => 'object',
                'properties' => [
                    'category' => ['type' => 'string', 'enum' => [$this->category]],
                ],
                'required' => ['category'],
            ],
            tags: new TagsCollection(['demo']),
        );
    }
}

final class CategoryToolFactory implements DynamicToolFactoryInterface
{
    public function getToolName(): string
    {
        return 'category_lookup';
    }

    public function getToolDescription(): string
    {
        return 'Looks up items in the configured category';
    }

    public function create(ConfigMap $config): DynamicToolInterface
    {
        $category = $config->all()['category'] ?? null;
        if (!is_string($category)) {
            throw new ToolConfigurationException('A category string is required.');
        }

        return new CategoryTool($category);
    }
}

$facade = AiToolCallFacadeBuilder::new()
    ->withSpiFactories([new EchoToolFactory(), new CategoryToolFactory()])
    ->withToolConfigs([
        'echo' => new ConfigMap([]),
        'category_lookup' => new ConfigMap(['category' => 'books']),
    ])
    ->build();

// Already configured dynamic instances can also be registered alongside static factories.
$directFacade = AiToolCallFacadeBuilder::new()
    ->withSpiFactories([new EchoToolFactory()])
    ->withDynamicTools(new DynamicToolCollection([new CategoryTool('books')]))
    ->build();

Static and dynamic SPI tools can be registered together and are exposed through the same facade. The dynamic factory's getToolName() is also used to select its ConfigMap from withToolConfigs().

Returning media from a tool

SPI tools can return media alongside the structured result. Media payloads use a MIME type, base64-encoded data, and an optional filename:

use AdachSoft\AiToolCall\SPI\Collection\KeyValueMap;
use AdachSoft\AiToolCall\SPI\Collection\ToolMediaCollection;
use AdachSoft\AiToolCall\SPI\Dto\ToolMediaDto;
use AdachSoft\AiToolCall\SPI\Dto\ToolCallResultDto as SpiResult;

return new SpiResult(
    toolName: 'image_tool',
    result: new KeyValueMap(['status' => 'created']),
    media: new ToolMediaCollection([
        new ToolMediaDto(
            mimeType: 'image/png',
            base64Data: base64_encode($imageBytes),
            filename: 'chart.png',
        ),
    ]),
);

The Public API returns these values in its own ToolMediaCollection; callers that do not provide media remain compatible and receive an empty collection.

Built-in tools

The builder registers these built-in tools by default:

  • current_datetime: returns the current date and time.
  • sleep: pauses execution for a required integer seconds parameter between 1 and 900, then returns the requested duration as slept_seconds.

After building the facade in the Quick Start example, call the tool with the same public request DTO:

$sleepResult = $facade->callTool(new ToolCallRequestDto(
    toolName: 'sleep',
    parameters: ['seconds' => 5],
));

var_dump($sleepResult->result); // ['slept_seconds' => 5]

Tool discovery & registration

  • No autoscan. The builder does not scan directories.
  • Register tools via:
    • SPI factories using withSpiFactories() and optional withToolConfigs() for configuration maps, or
    • Direct SPI tools using withSpiTools() when tools are already fully configured.

Error handling

  • Public API throws PublicApi\Exception\ToolCallFailedException on errors during tool execution.
  • Public API throws PublicApi\Exception\ToolRegistrationException when tool registration or configuration fails while building the facade (e.g. duplicate tool names or invalid factory/config types).
  • SPI exceptions:
    • SPI\Exception\InvalidToolCallException
    • SPI\Exception\ToolExecutionException
    • SPI\Exception\ToolConfigurationException These are mapped through the adapter when calling SPI tools through the Domain.

Versioning

  • Semantic Versioning.
  • Package version is controlled by Git tags (do not set version in composer.json).

License

MIT