adachsoft / ai-tool-call
Unified AI tool-calling abstraction for PHP 8.3 with a clean Public API and an extensible SPI for custom tools.
Requires
- php: ^8.3
- adachsoft/collection: ^3.0
- psr/log: ^3.0
Requires (Dev)
- adachsoft/php-code-style: ^0.7.3
- friendsofphp/php-cs-fixer: ^3.88
- phpstan/phpstan: ^2.1
- phpunit/phpunit: ^12.4
- rector/rector: ^2.8
- symplify/phpstan-rules: ^14.19
Suggests
None
Provides
None
Conflicts
None
Replaces
None
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\AiToolCallFacadeInterfacecallTool(ToolCallRequestDto): ToolCallResultDtolistAvailableTools(): AvailableToolCollectionlistAvailableToolsByTags(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)ToolMediaCollectionAvailableToolDto(string $name, string $description, array $parametersSchema, array $tags)AvailableToolCollection
SPI (Service Provider Interface)
Implement custom tools by fulfilling the SPI contracts.
AdachSoft\AiToolCall\SPI\ToolInterfacecallTool(ToolCallRequestDto): ToolCallResultDtostatic getDefinition(): ToolDefinitionDto
AdachSoft\AiToolCall\SPI\DynamicToolInterfacecallTool(ToolCallRequestDto): ToolCallResultDtogetDefinition(): ToolDefinitionDtofor the configured instance
AdachSoft\AiToolCall\SPI\Factory\ToolFactoryInterfacegetToolClass(): stringcreate(ConfigMap $config): ToolInterface
AdachSoft\AiToolCall\SPI\Factory\DynamicToolFactoryInterfacegetToolName(): stringgetToolDescription(): stringcreate(ConfigMap $config): DynamicToolInterface
ToolDefinitionDtoname: stringdescription: stringparametersSchema: array<string, mixed>tags: TagsCollectionenabled: 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 integersecondsparameter between 1 and 900, then returns the requested duration asslept_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 optionalwithToolConfigs()for configuration maps, or - Direct SPI tools using
withSpiTools()when tools are already fully configured.
- SPI factories using
Error handling
- Public API throws
PublicApi\Exception\ToolCallFailedExceptionon errors during tool execution. - Public API throws
PublicApi\Exception\ToolRegistrationExceptionwhen tool registration or configuration fails while building the facade (e.g. duplicate tool names or invalid factory/config types). - SPI exceptions:
SPI\Exception\InvalidToolCallExceptionSPI\Exception\ToolExecutionExceptionSPI\Exception\ToolConfigurationExceptionThese 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