diff --git a/README.md b/README.md index 5b09c0d..6a95d00 100644 --- a/README.md +++ b/README.md @@ -35,7 +35,7 @@ use PapiAI\Anthropic\AnthropicProvider; $agent = new Agent( provider: new AnthropicProvider(apiKey: $_ENV['ANTHROPIC_API_KEY']), - model: 'claude-sonnet-4-20250514', + model: 'claude-sonnet-5-5', instructions: 'You are a helpful assistant.', ); @@ -63,7 +63,7 @@ $weatherTool = Tool::make( $agent = new Agent( provider: $provider, - model: 'claude-sonnet-4-20250514', + model: 'claude-sonnet-5-5', tools: [$weatherTool], ); @@ -96,7 +96,7 @@ class WebTools $agent = new Agent( provider: $provider, - model: 'claude-sonnet-4-20250514', + model: 'claude-sonnet-5-5', tools: Tool::fromClass(WebTools::class), ); ``` @@ -189,7 +189,7 @@ Add observability to your agent: ```php $agent = new Agent( provider: $provider, - model: 'claude-sonnet-4-20250514', + model: 'claude-sonnet-5-5', tools: $tools, hooks: [ 'beforeToolCall' => function (string $name, array $input) { @@ -229,17 +229,41 @@ $conversation->addUser('Tell me a joke'); $messages = $conversation->getMessages(); ``` +## Why a Response Stopped + +Every provider reports why the model stopped in the same words: + +```php +use PapiAI\Core\StopReason; + +$response = $agent->run('Summarise this repository'); + +if ($response->isTruncated()) { + // The output ceiling cut the answer short: raise maxTokens and ask again. +} + +match ($response->stoppedBecause) { + StopReason::Stop => 'finished', + StopReason::ToolCalls => 'wants tools run', + StopReason::MaxTokens => 'cut short', + StopReason::Refused => 'declined or filtered', + StopReason::Other => 'something else', +}; +``` + +The provider's own string is still on `$response->stopReason`. + ## Configuration Options ```php $agent = new Agent( provider: $provider, - model: 'claude-sonnet-4-20250514', + model: 'claude-sonnet-5-5', instructions: 'System prompt here', tools: [...], hooks: [...], maxTokens: 4096, // Max response tokens - temperature: 0.7, // 0.0 = deterministic, 1.0 = creative + temperature: 0.7, // Only on models that still take it; current Claude and Gemini refuse it maxTurns: 10, // Max tool-use loops before stopping ); ``` @@ -253,7 +277,7 @@ use PapiAI\Anthropic\AnthropicProvider; $provider = new AnthropicProvider( apiKey: $_ENV['ANTHROPIC_API_KEY'], - defaultModel: 'claude-sonnet-4-20250514', + defaultModel: 'claude-sonnet-5-5', ); ``` @@ -264,17 +288,44 @@ use PapiAI\Google\GoogleProvider; $provider = new GoogleProvider( apiKey: $_ENV['GOOGLE_API_KEY'], - defaultModel: GoogleProvider::MODEL_3_6_FLASH, + defaultModel: GoogleProvider::MODEL_3_8_FLASH, ); -// Available models -GoogleProvider::MODEL_3_6_FLASH // gemini-3.6-flash (default) -GoogleProvider::MODEL_3_5_FLASH // gemini-3.5-flash -GoogleProvider::MODEL_3_1_PRO // gemini-3.1-pro-preview -GoogleProvider::MODEL_2_5_PRO // gemini-2.5-pro -GoogleProvider::MODEL_2_0_FLASH // gemini-2.0-flash +// Some of the available models +GoogleProvider::MODEL_4_HYDROGEN // gemini-4-hydrogen +GoogleProvider::MODEL_4_CARBON // gemini-4-carbon +GoogleProvider::MODEL_3_8_FLASH // gemini-3.8-flash (default) +GoogleProvider::MODEL_3_1_PRO // gemini-3.1-pro-preview +GoogleProvider::MODEL_2_5_PRO // gemini-2.5-pro +``` + +### Choosing a Provider by Name + +An application that lets its users pick a provider in configuration does not need to know any +provider's class or constructor. Every provider package ships a factory, and `ComposerDiscovery` +finds the ones that are installed: + +```php +use PapiAI\Core\Factory\ComposerDiscovery; +use PapiAI\Core\Factory\ProviderRegistry; + +$registry = new ProviderRegistry(new ComposerDiscovery()); + +$provider = $registry->create('google', ['api_key' => $_ENV['GOOGLE_API_KEY']]); + +foreach ($registry->installed() as $factory) { + echo $factory->package(), ': ', $factory->name(), "\n"; + + foreach ($factory->settings() as $setting) { + echo ' ', $setting->name, $setting->required ? ' (required)' : '', ': ', $setting->description, "\n"; + } +} ``` +Setting names are snake_case (`api_key`, `base_url`, `model`, `max_tokens`, `effort`). A missing, +unknown or mistyped setting throws `ConfigurationException`, an `InvalidArgumentException`, before +any request is made. The registry accepts any list of factories, so tests can hand it their own. + ## Creating Custom Providers Implement `ProviderInterface`: @@ -302,6 +353,41 @@ class MyProvider implements ProviderInterface } ``` +To make it discoverable by name, ship a factory with it. Extend `AbstractProviderFactory`, +declare your settings, and build the provider from them: + +```php +use PapiAI\Core\Contracts\ProviderInterface; +use PapiAI\Core\Factory\AbstractProviderFactory; +use PapiAI\Core\Factory\Setting; +use PapiAI\Core\Factory\SettingValues; + +final class MyProviderFactory extends AbstractProviderFactory +{ + public function name(): string { return 'my-provider'; } + public function package(): string { return 'acme/my-provider'; } + + public function settings(): array + { + return [new Setting('api_key', true, 'My API key')]; + } + + protected function build(SettingValues $values): ProviderInterface + { + return new MyProvider($values->string('api_key')); + } +} +``` + +Then declare the package type and the factory in its `composer.json`: + +```json +{ + "type": "papi-provider", + "extra": {"papi": {"factory": "Acme\\MyProviderFactory"}} +} +``` + ## Testing ```bash diff --git a/composer.json b/composer.json index ec68486..570808d 100644 --- a/composer.json +++ b/composer.json @@ -10,7 +10,8 @@ } ], "require": { - "php": "^8.2" + "php": "^8.2", + "composer-runtime-api": "^2.0" }, "suggest": { "psr/log": "Required for LoggingMiddleware (^3.0)", diff --git a/composer.lock b/composer.lock index b6155d4..3bc46cd 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "64ae449a2d91e274751bb62341771e92", + "content-hash": "65b1f35f88b3eca37612317438ad6976", "packages": [], "packages-dev": [ { @@ -7261,8 +7261,9 @@ "prefer-stable": false, "prefer-lowest": false, "platform": { - "php": "^8.2" + "php": "^8.2", + "composer-runtime-api": "^2.0" }, "platform-dev": {}, - "plugin-api-version": "2.6.0" + "plugin-api-version": "2.9.0" } diff --git a/docs/agentic-php.md b/docs/agentic-php.md index 7804a92..9928bc7 100644 --- a/docs/agentic-php.md +++ b/docs/agentic-php.md @@ -20,7 +20,7 @@ $weatherTool = Tool::make( $agent = new Agent( provider: $provider, - model: 'claude-sonnet-4-20250514', + model: 'claude-sonnet-5-5', tools: [$weatherTool], ); @@ -53,7 +53,7 @@ class WebTools $agent = new Agent( provider: $provider, - model: 'claude-sonnet-4-20250514', + model: 'claude-sonnet-5-5', tools: Tool::fromClass(WebTools::class), ); ``` @@ -143,7 +143,7 @@ Add observability to your agent: ```php $agent = new Agent( provider: $provider, - model: 'claude-sonnet-4-20250514', + model: 'claude-sonnet-5-5', tools: $tools, hooks: [ 'beforeToolCall' => function (string $name, array $input) { @@ -171,7 +171,7 @@ use PapiAI\Core\Middleware\CacheMiddleware; $agent = Agent::build() ->provider($provider) - ->model('claude-sonnet-4-20250514') + ->model('claude-sonnet-5-5') ->addMiddleware(new RetryMiddleware(maxRetries: 3)) ->addMiddleware(new RateLimitMiddleware(maxRequests: 60, perSeconds: 60)) ->addMiddleware(new LoggingMiddleware($psrLogger)) @@ -201,12 +201,12 @@ $messages = $conversation->getMessages(); ```php $agent = new Agent( provider: $provider, - model: 'claude-sonnet-4-20250514', + model: 'claude-sonnet-5-5', instructions: 'System prompt here', tools: [...], hooks: [...], maxTokens: 4096, // Max response tokens - temperature: 0.7, // 0.0 = deterministic, 1.0 = creative + temperature: 0.7, // Only on models that still take it; current Claude and Gemini refuse it maxTurns: 10, // Max tool-use loops before stopping ); ``` diff --git a/docs/simple-example.md b/docs/simple-example.md index 92d0d39..3898641 100644 --- a/docs/simple-example.md +++ b/docs/simple-example.md @@ -6,7 +6,7 @@ use PapiAI\Anthropic\AnthropicProvider; $agent = new Agent( provider: new AnthropicProvider(apiKey: $_ENV['ANTHROPIC_API_KEY']), - model: 'claude-sonnet-4-20250514', + model: 'claude-sonnet-5-5', instructions: 'You are a helpful assistant.', ); @@ -19,10 +19,9 @@ Or use the fluent builder: ```php $agent = Agent::build() ->provider(new AnthropicProvider(apiKey: $_ENV['ANTHROPIC_API_KEY'])) - ->model('claude-sonnet-4-20250514') + ->model('claude-sonnet-5-5') ->instructions('You are a helpful assistant.') ->maxTokens(4096) - ->temperature(0.7) ->create(); $response = $agent->run('Tell me a joke'); diff --git a/src/Agent.php b/src/Agent.php index 0f3e5b2..a78a71e 100644 --- a/src/Agent.php +++ b/src/Agent.php @@ -407,13 +407,7 @@ private function executeTool(ToolCall $toolCall, mixed $context = null): mixed private function finalizeResponse(Response $response, array $messages, ?Schema $outputSchema): Response { if ($outputSchema === null) { - return new Response( - text: $response->text, - toolCalls: $response->toolCalls, - messages: $messages, - usage: $response->usage, - stopReason: $response->stopReason, - ); + return $response->withMessages($messages); } // Try to parse JSON from the response @@ -441,13 +435,6 @@ private function finalizeResponse(Response $response, array $messages, ?Schema $ // Validate against schema $outputSchema->parse($data); - return new Response( - text: $response->text, - data: $data, - toolCalls: $response->toolCalls, - messages: $messages, - usage: $response->usage, - stopReason: $response->stopReason, - ); + return $response->withMessages($messages)->withData($data); } } diff --git a/src/Contracts/ProviderFactoryInterface.php b/src/Contracts/ProviderFactoryInterface.php new file mode 100644 index 0000000..565537f --- /dev/null +++ b/src/Contracts/ProviderFactoryInterface.php @@ -0,0 +1,51 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace PapiAI\Core\Contracts; + +use PapiAI\Core\Exception\ConfigurationException; +use PapiAI\Core\Factory\Setting; + +/** + * Builds one provider from plain settings, so an application can choose a provider by name + * from its configuration without knowing the provider's class or constructor. + * + * Each provider package ships one, named in its composer.json under extra.papi.factory. + */ +interface ProviderFactoryInterface +{ + /** + * The name a configuration selects this provider by, such as "google". + */ + public function name(): string; + + /** + * The Composer package that ships this provider, such as "papi-ai/google". + */ + public function package(): string; + + /** + * Every setting create() accepts. + * + * @return list + */ + public function settings(): array; + + /** + * @param array $settings Setting values keyed by Setting::$name + * + * @throws ConfigurationException When a setting is unknown, missing or of the wrong type + */ + public function create(array $settings): ProviderInterface; +} diff --git a/src/Exception/ConfigurationException.php b/src/Exception/ConfigurationException.php new file mode 100644 index 0000000..9ee0c98 --- /dev/null +++ b/src/Exception/ConfigurationException.php @@ -0,0 +1,24 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace PapiAI\Core\Exception; + +use InvalidArgumentException; + +/** + * A provider cannot be built from the settings it was given. Thrown before any HTTP call. + */ +final class ConfigurationException extends InvalidArgumentException +{ +} diff --git a/src/Factory/AbstractProviderFactory.php b/src/Factory/AbstractProviderFactory.php new file mode 100644 index 0000000..ec6b12a --- /dev/null +++ b/src/Factory/AbstractProviderFactory.php @@ -0,0 +1,81 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace PapiAI\Core\Factory; + +use PapiAI\Core\Contracts\ProviderFactoryInterface; +use PapiAI\Core\Contracts\ProviderInterface; +use PapiAI\Core\Exception\ConfigurationException; + +/** + * Checks the settings against what the factory declares, then hands them to build(). + * + * Unknown keys are refused, so a misspelt setting fails instead of being ignored. + */ +abstract class AbstractProviderFactory implements ProviderFactoryInterface +{ + final public function create(array $settings): ProviderInterface + { + $declared = []; + + foreach ($this->settings() as $setting) { + $declared[$setting->name] = $setting; + } + + foreach (array_keys($settings) as $key) { + if (!isset($declared[$key])) { + throw new ConfigurationException(sprintf( + 'Provider "%s" has no setting "%s". It takes: %s.', + $this->name(), + $key, + implode(', ', array_keys($declared)), + )); + } + } + + foreach ($declared as $name => $setting) { + if ($setting->required && in_array($settings[$name] ?? null, [null, ''], true)) { + throw new ConfigurationException(sprintf( + 'Provider "%s" needs the "%s" setting: %s.', + $this->name(), + $name, + $setting->description, + )); + } + } + + return $this->build(new SettingValues($this->name(), $settings)); + } + + /** + * The constructor arguments that were given, so the provider's own defaults apply to the rest. + * + * Spread the result into the constructor: `new MyProvider(...$this->argumentsGiven([...]))`. + * + * @param array $arguments Constructor arguments by parameter name, null when not given + * + * @return array + */ + protected function argumentsGiven(array $arguments): array + { + return array_filter($arguments, static fn (mixed $value): bool => $value !== null); + } + + /** + * Construct the provider. Every required setting is present by the time this runs. + * + * @throws ConfigurationException When a value has the wrong type + */ + abstract protected function build(SettingValues $values): ProviderInterface; +} diff --git a/src/Factory/ComposerDiscovery.php b/src/Factory/ComposerDiscovery.php new file mode 100644 index 0000000..271afdf --- /dev/null +++ b/src/Factory/ComposerDiscovery.php @@ -0,0 +1,82 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace PapiAI\Core\Factory; + +use Composer\InstalledVersions; +use Generator; +use IteratorAggregate; +use PapiAI\Core\Contracts\ProviderFactoryInterface; +use PapiAI\Core\Exception\ConfigurationException; + +/** + * The factories of every installed provider package. + * + * A provider package declares the Composer type "papi-provider" and names its factory class + * under extra.papi.factory in its composer.json. + * + * @implements IteratorAggregate + */ +final class ComposerDiscovery implements IteratorAggregate +{ + public const PACKAGE_TYPE = 'papi-provider'; + + /** + * @return Generator + * + * @throws ConfigurationException When a provider package names no usable factory + */ + public function getIterator(): Generator + { + foreach (array_unique(InstalledVersions::getInstalledPackagesByType(self::PACKAGE_TYPE)) as $package) { + yield $this->factoryOf($package); + } + } + + private function factoryOf(string $package): ProviderFactoryInterface + { + $class = $this->factoryClassNamedBy($package); + + if (!class_exists($class)) { + throw new ConfigurationException(sprintf('Package "%s" names factory "%s", which does not exist.', $package, $class)); + } + + $factory = new $class(); + + if (!$factory instanceof ProviderFactoryInterface) { + throw new ConfigurationException(sprintf( + 'Package "%s" names factory "%s", which does not implement %s.', + $package, + $class, + ProviderFactoryInterface::class, + )); + } + + return $factory; + } + + private function factoryClassNamedBy(string $package): string + { + $manifest = InstalledVersions::getInstallPath($package) . '/composer.json'; + $contents = is_file($manifest) ? file_get_contents($manifest) : false; + $decoded = is_string($contents) ? json_decode($contents, true) : null; + $class = is_array($decoded) ? ($decoded['extra']['papi']['factory'] ?? null) : null; + + if (!is_string($class) || $class === '') { + throw new ConfigurationException(sprintf('Package "%s" is a papi-provider but names no factory in extra.papi.factory.', $package)); + } + + return $class; + } +} diff --git a/src/Factory/ProviderRegistry.php b/src/Factory/ProviderRegistry.php new file mode 100644 index 0000000..49f7863 --- /dev/null +++ b/src/Factory/ProviderRegistry.php @@ -0,0 +1,86 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace PapiAI\Core\Factory; + +use PapiAI\Core\Contracts\ProviderFactoryInterface; +use PapiAI\Core\Contracts\ProviderInterface; +use PapiAI\Core\Exception\ConfigurationException; + +/** + * The providers an application can build, by name. + * + * Built from any list of factories: ComposerDiscovery for what is installed, or a plain array + * where the application wants to choose. + */ +final class ProviderRegistry +{ + /** @var array */ + private array $factories = []; + + /** + * @param iterable $factories + * + * @throws ConfigurationException When two factories claim the same name + */ + public function __construct(iterable $factories) + { + foreach ($factories as $factory) { + $claimed = $this->factories[$factory->name()] ?? null; + + if ($claimed !== null) { + throw new ConfigurationException(sprintf( + 'Both "%s" and "%s" provide "%s".', + $claimed->package(), + $factory->package(), + $factory->name(), + )); + } + + $this->factories[$factory->name()] = $factory; + } + } + + /** + * @return list + */ + public function installed(): array + { + return array_values($this->factories); + } + + /** + * @param array $settings + * + * @throws ConfigurationException When no factory has that name, or the settings do not fit it + */ + public function create(string $provider, array $settings): ProviderInterface + { + $factory = $this->factories[$provider] ?? null; + + if ($factory !== null) { + return $factory->create($settings); + } + + if ($this->factories === []) { + throw new ConfigurationException(sprintf('Provider "%s" is not installed, and no papi provider package is.', $provider)); + } + + throw new ConfigurationException(sprintf( + 'Provider "%s" is not installed. Installed: %s.', + $provider, + implode(', ', array_map(static fn (string $name): string => '"' . $name . '"', array_keys($this->factories))), + )); + } +} diff --git a/src/Factory/Setting.php b/src/Factory/Setting.php new file mode 100644 index 0000000..c1b0d45 --- /dev/null +++ b/src/Factory/Setting.php @@ -0,0 +1,33 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace PapiAI\Core\Factory; + +/** + * One setting a provider factory accepts. + */ +final class Setting +{ + /** + * @param string $name The key, in snake_case, such as "api_key" + * @param bool $required Whether the provider cannot be built without it + * @param string $description What it is, short enough for a setup prompt + */ + public function __construct( + public readonly string $name, + public readonly bool $required, + public readonly string $description, + ) { + } +} diff --git a/src/Factory/SettingValues.php b/src/Factory/SettingValues.php new file mode 100644 index 0000000..8e81eb2 --- /dev/null +++ b/src/Factory/SettingValues.php @@ -0,0 +1,130 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace PapiAI\Core\Factory; + +use PapiAI\Core\Effort; +use PapiAI\Core\Exception\ConfigurationException; + +/** + * The settings handed to a factory, read back as the types a provider constructor takes. + * + * An empty string counts as not given, since that is what an unset environment variable or a + * blank configuration entry produces. + */ +final class SettingValues +{ + /** + * @param array $values + */ + public function __construct( + private readonly string $provider, + private readonly array $values, + ) { + } + + /** + * @throws ConfigurationException When the value is missing with no default, or not a string + */ + public function string(string $name, ?string $default = null): string + { + $value = $this->stringOrNull($name) ?? $default; + + if ($value === null) { + throw new ConfigurationException(sprintf('Provider "%s" needs the "%s" setting.', $this->provider, $name)); + } + + return $value; + } + + /** + * @throws ConfigurationException When the value is given but is not a string + */ + public function stringOrNull(string $name): ?string + { + $value = $this->given($name); + + if ($value === null || is_string($value)) { + return $value; + } + + throw $this->wrongType($name, 'a string', $value); + } + + /** + * @throws ConfigurationException When the value is given but is not a whole number + */ + public function intOrNull(string $name): ?int + { + $value = $this->given($name); + + if ($value === null) { + return null; + } + + if (is_int($value)) { + return $value; + } + + if (is_string($value) && ctype_digit($value)) { + return (int) $value; + } + + throw $this->wrongType($name, 'an integer', $value); + } + + /** + * @throws ConfigurationException When the value is given but names no Effort + */ + public function effort(string $name = 'effort'): ?Effort + { + $value = $this->given($name); + + if ($value === null || $value instanceof Effort) { + return $value; + } + + $effort = is_string($value) ? Effort::tryFrom($value) : null; + + if ($effort !== null) { + return $effort; + } + + throw new ConfigurationException(sprintf( + 'Setting "%s" of provider "%s" must be one of %s; %s given.', + $name, + $this->provider, + implode(', ', array_map(static fn (Effort $effort): string => '"' . $effort->value . '"', Effort::cases())), + is_string($value) ? '"' . $value . '"' : get_debug_type($value), + )); + } + + private function given(string $name): mixed + { + $value = $this->values[$name] ?? null; + + return $value === '' ? null : $value; + } + + private function wrongType(string $name, string $expected, mixed $value): ConfigurationException + { + return new ConfigurationException(sprintf( + 'Setting "%s" of provider "%s" must be %s, %s given.', + $name, + $this->provider, + $expected, + get_debug_type($value), + )); + } +} diff --git a/src/Response.php b/src/Response.php index dfa33ec..a4d7425 100644 --- a/src/Response.php +++ b/src/Response.php @@ -36,7 +36,8 @@ final class Response * @param array $toolCalls Tool calls made by the LLM * @param array $messages Full conversation history * @param Usage|array $usage Token usage (a raw provider array is accepted and normalised) - * @param string|null $stopReason Why the response ended + * @param string|null $stopReason Why the response ended, in the provider's own words + * @param StopReason $stoppedBecause Why the response ended, in the same words for every provider */ public function __construct( public readonly string $text, @@ -45,6 +46,7 @@ public function __construct( public readonly array $messages = [], Usage|array $usage = [], public readonly ?string $stopReason = null, + public readonly StopReason $stoppedBecause = StopReason::Other, ) { $this->usage = is_array($usage) ? Usage::fromArray($usage) : $usage; } @@ -59,6 +61,14 @@ public function hasToolCalls(): bool return !empty($this->toolCalls); } + /** + * Whether the output ceiling cut the answer short. + */ + public function isTruncated(): bool + { + return $this->stoppedBecause === StopReason::MaxTokens; + } + /** * Check if the response has structured data. * @@ -129,6 +139,13 @@ public static function fromAnthropic(array $response, array $messages = []): sel messages: $messages, usage: $response['usage'] ?? [], stopReason: $response['stop_reason'] ?? null, + stoppedBecause: match ($response['stop_reason'] ?? null) { + 'end_turn', 'stop_sequence' => StopReason::Stop, + 'max_tokens', 'model_context_window_exceeded' => StopReason::MaxTokens, + 'tool_use' => StopReason::ToolCalls, + 'refusal' => StopReason::Refused, + default => StopReason::Other, + }, ); } @@ -156,6 +173,13 @@ public static function fromOpenAI(array $response, array $messages = []): self messages: $messages, usage: $response['usage'] ?? [], stopReason: $choice['finish_reason'] ?? null, + stoppedBecause: $toolCalls !== [] ? StopReason::ToolCalls : match ($choice['finish_reason'] ?? null) { + 'stop' => StopReason::Stop, + 'length', 'model_length' => StopReason::MaxTokens, + 'tool_calls', 'function_call' => StopReason::ToolCalls, + 'content_filter' => StopReason::Refused, + default => StopReason::Other, + }, ); } @@ -175,6 +199,25 @@ public function withData(array $data): self messages: $this->messages, usage: $this->usage, stopReason: $this->stopReason, + stoppedBecause: $this->stoppedBecause, + ); + } + + /** + * Return a new Response carrying a different conversation history. + * + * @param array $messages + */ + public function withMessages(array $messages): self + { + return new self( + text: $this->text, + data: $this->data, + toolCalls: $this->toolCalls, + messages: $messages, + usage: $this->usage, + stopReason: $this->stopReason, + stoppedBecause: $this->stoppedBecause, ); } } diff --git a/src/StopReason.php b/src/StopReason.php new file mode 100644 index 0000000..71750b4 --- /dev/null +++ b/src/StopReason.php @@ -0,0 +1,38 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace PapiAI\Core; + +/** + * Why a model stopped, in one vocabulary for every provider. + * + * The provider's own string stays on Response::$stopReason; this is what to branch on. + */ +enum StopReason: string +{ + /** The model finished its turn. */ + case Stop = 'stop'; + + /** The model wants tools run before it continues. */ + case ToolCalls = 'tool_calls'; + + /** The output ceiling cut the answer short. */ + case MaxTokens = 'max_tokens'; + + /** The model declined, or a content filter stopped it. */ + case Refused = 'refused'; + + /** Anything else, or the provider did not say. */ + case Other = 'other'; +} diff --git a/tests/Fixtures/Discovery/missing-class/composer.json b/tests/Fixtures/Discovery/missing-class/composer.json new file mode 100644 index 0000000..6e3ecf5 --- /dev/null +++ b/tests/Fixtures/Discovery/missing-class/composer.json @@ -0,0 +1,9 @@ +{ + "name": "acme/missing-class", + "type": "papi-provider", + "extra": { + "papi": { + "factory": "Acme\\Missing\\Factory" + } + } +} diff --git a/tests/Fixtures/Discovery/no-factory/composer.json b/tests/Fixtures/Discovery/no-factory/composer.json new file mode 100644 index 0000000..3625307 --- /dev/null +++ b/tests/Fixtures/Discovery/no-factory/composer.json @@ -0,0 +1,5 @@ +{ + "name": "acme/no-factory", + "type": "papi-provider", + "extra": {} +} diff --git a/tests/Fixtures/Discovery/not-a-factory/composer.json b/tests/Fixtures/Discovery/not-a-factory/composer.json new file mode 100644 index 0000000..087f27e --- /dev/null +++ b/tests/Fixtures/Discovery/not-a-factory/composer.json @@ -0,0 +1,9 @@ +{ + "name": "acme/not-a-factory", + "type": "papi-provider", + "extra": { + "papi": { + "factory": "PapiAI\\Core\\Tests\\Fixtures\\NotAFactory" + } + } +} diff --git a/tests/Fixtures/Discovery/provider/composer.json b/tests/Fixtures/Discovery/provider/composer.json new file mode 100644 index 0000000..e94e8cb --- /dev/null +++ b/tests/Fixtures/Discovery/provider/composer.json @@ -0,0 +1,9 @@ +{ + "name": "acme/provider", + "type": "papi-provider", + "extra": { + "papi": { + "factory": "PapiAI\\Core\\Tests\\Fixtures\\FakeProviderFactory" + } + } +} diff --git a/tests/Fixtures/FakeProvider.php b/tests/Fixtures/FakeProvider.php new file mode 100644 index 0000000..7ed5603 --- /dev/null +++ b/tests/Fixtures/FakeProvider.php @@ -0,0 +1,64 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace PapiAI\Core\Tests\Fixtures; + +use PapiAI\Core\Contracts\ProviderInterface; +use PapiAI\Core\Effort; +use PapiAI\Core\Response; + +/** + * A provider that records how its factory built it. + */ +final class FakeProvider implements ProviderInterface +{ + public function __construct( + public readonly string $apiKey, + public readonly string $model = 'fake-1', + public readonly int $maxTokens = 4096, + public readonly ?Effort $effort = null, + public readonly ?string $baseUrl = null, + ) { + } + + public function chat(array $messages, array $options = []): Response + { + return new Response(''); + } + + public function stream(array $messages, array $options = []): iterable + { + return []; + } + + public function supportsTool(): bool + { + return false; + } + + public function supportsVision(): bool + { + return false; + } + + public function supportsStructuredOutput(): bool + { + return false; + } + + public function getName(): string + { + return 'fake'; + } +} diff --git a/tests/Fixtures/FakeProviderFactory.php b/tests/Fixtures/FakeProviderFactory.php new file mode 100644 index 0000000..a1595ac --- /dev/null +++ b/tests/Fixtures/FakeProviderFactory.php @@ -0,0 +1,61 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace PapiAI\Core\Tests\Fixtures; + +use PapiAI\Core\Contracts\ProviderInterface; +use PapiAI\Core\Factory\AbstractProviderFactory; +use PapiAI\Core\Factory\Setting; +use PapiAI\Core\Factory\SettingValues; + +final class FakeProviderFactory extends AbstractProviderFactory +{ + public function __construct( + private readonly string $name = 'fake', + private readonly string $package = 'papi-ai/fake', + ) { + } + + public function name(): string + { + return $this->name; + } + + public function package(): string + { + return $this->package; + } + + public function settings(): array + { + return [ + new Setting('api_key', true, 'Fake API key'), + new Setting('model', false, 'Default model, fake-1 unless set'), + new Setting('max_tokens', false, 'Output ceiling, 4096 unless set'), + new Setting('effort', false, 'Default reasoning effort'), + new Setting('base_url', false, 'Server address'), + ]; + } + + protected function build(SettingValues $values): ProviderInterface + { + return new FakeProvider(...$this->argumentsGiven([ + 'apiKey' => $values->string('api_key'), + 'model' => $values->stringOrNull('model'), + 'maxTokens' => $values->intOrNull('max_tokens'), + 'effort' => $values->effort(), + 'baseUrl' => $values->stringOrNull('base_url'), + ])); + } +} diff --git a/tests/Fixtures/NotAFactory.php b/tests/Fixtures/NotAFactory.php new file mode 100644 index 0000000..6c69c87 --- /dev/null +++ b/tests/Fixtures/NotAFactory.php @@ -0,0 +1,19 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace PapiAI\Core\Tests\Fixtures; + +final class NotAFactory +{ +} diff --git a/tests/Unit/ComposerDiscoveryTest.php b/tests/Unit/ComposerDiscoveryTest.php new file mode 100644 index 0000000..76330d8 --- /dev/null +++ b/tests/Unit/ComposerDiscoveryTest.php @@ -0,0 +1,85 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +use Composer\InstalledVersions; +use PapiAI\Core\Exception\ConfigurationException; +use PapiAI\Core\Factory\ComposerDiscovery; +use PapiAI\Core\Tests\Fixtures\FakeProviderFactory; + +/** + * Pretends Composer installed the given fixture packages, each under tests/Fixtures/Discovery. + * + * @param array $packages package name => type + */ +function installFixtures(array $packages): void +{ + $versions = []; + + foreach ($packages as $name => $type) { + $versions[$name] = [ + 'pretty_version' => '1.0.0', + 'version' => '1.0.0.0', + 'reference' => null, + 'type' => $type, + 'install_path' => __DIR__ . '/../Fixtures/Discovery/' . substr($name, strlen('acme/')), + 'aliases' => [], + 'dev_requirement' => false, + ]; + } + + InstalledVersions::reload([ + 'root' => ['name' => 'acme/app', 'pretty_version' => '1.0.0', 'version' => '1.0.0.0', 'reference' => null, 'type' => 'project', 'install_path' => __DIR__, 'aliases' => [], 'dev' => true], + 'versions' => $versions, + ]); +} + +describe('Composer discovery', function () { + afterEach(function () { + InstalledVersions::reload(null); + }); + + it('finds the factory each papi-provider package names, and only those', function () { + installFixtures(['acme/provider' => 'papi-provider', 'acme/no-factory' => 'library']); + + $factories = iterator_to_array(new ComposerDiscovery(), false); + + expect($factories)->toHaveCount(1); + expect($factories[0])->toBeInstanceOf(FakeProviderFactory::class); + }); + + it('finds nothing when no provider package is installed', function () { + expect(iterator_to_array(new ComposerDiscovery(), false))->toBe([]); + }); + + it('refuses a provider package that names no factory', function () { + installFixtures(['acme/no-factory' => 'papi-provider']); + + expect(fn () => iterator_to_array(new ComposerDiscovery())) + ->toThrow(ConfigurationException::class, 'Package "acme/no-factory" is a papi-provider but names no factory in extra.papi.factory.'); + }); + + it('refuses a factory class that does not exist', function () { + installFixtures(['acme/missing-class' => 'papi-provider']); + + expect(fn () => iterator_to_array(new ComposerDiscovery())) + ->toThrow(ConfigurationException::class, 'Package "acme/missing-class" names factory "Acme\\Missing\\Factory", which does not exist.'); + }); + + it('refuses a class that is not a provider factory', function () { + installFixtures(['acme/not-a-factory' => 'papi-provider']); + + expect(fn () => iterator_to_array(new ComposerDiscovery())) + ->toThrow(ConfigurationException::class, 'which does not implement PapiAI\\Core\\Contracts\\ProviderFactoryInterface.'); + }); +}); diff --git a/tests/Unit/ProviderFactoryTest.php b/tests/Unit/ProviderFactoryTest.php new file mode 100644 index 0000000..89b99a7 --- /dev/null +++ b/tests/Unit/ProviderFactoryTest.php @@ -0,0 +1,87 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +use PapiAI\Core\Effort; +use PapiAI\Core\Exception\ConfigurationException; +use PapiAI\Core\Factory\Setting; +use PapiAI\Core\Factory\SettingValues; +use PapiAI\Core\Tests\Fixtures\FakeProvider; +use PapiAI\Core\Tests\Fixtures\FakeProviderFactory; + +describe('A provider factory', function () { + beforeEach(function () { + $this->factory = new FakeProviderFactory(); + }); + + it('describes itself for a setup prompt', function () { + expect($this->factory->name())->toBe('fake'); + expect($this->factory->package())->toBe('papi-ai/fake'); + expect($this->factory->settings()[0])->toEqual(new Setting('api_key', true, 'Fake API key')); + }); + + it('builds the provider from the settings it was given', function () { + $provider = $this->factory->create(['api_key' => 'k', 'model' => 'fake-2', 'max_tokens' => 512, 'effort' => 'high', 'base_url' => 'http://h']); + + expect($provider)->toEqual(new FakeProvider('k', 'fake-2', 512, Effort::High, 'http://h')); + }); + + it('leaves the optional settings it was not given to the provider\'s own defaults', function () { + expect($this->factory->create(['api_key' => 'k']))->toEqual(new FakeProvider('k', 'fake-1', 4096, null, null)); + }); + + it('treats an empty string as not given', function () { + expect($this->factory->create(['api_key' => 'k', 'model' => '', 'base_url' => '']))->toEqual(new FakeProvider('k', 'fake-1', 4096, null, null)); + }); + + it('accepts a number written as a string, as an environment variable would be', function () { + expect($this->factory->create(['api_key' => 'k', 'max_tokens' => '2048'])->maxTokens)->toBe(2048); + }); + + it('refuses a setting it does not know, so a typo fails loudly', function () { + expect(fn () => $this->factory->create(['apikey' => 'k'])) + ->toThrow(ConfigurationException::class, 'Provider "fake" has no setting "apikey". It takes: api_key, model, max_tokens, effort, base_url.'); + }); + + it('refuses to build without a required setting, saying what it is', function () { + foreach ([[], ['api_key' => ''], ['api_key' => null]] as $settings) { + expect(fn () => $this->factory->create($settings)) + ->toThrow(ConfigurationException::class, 'Provider "fake" needs the "api_key" setting: Fake API key.'); + } + }); + + it('refuses a value of the wrong type', function () { + expect(fn () => $this->factory->create(['api_key' => 'k', 'max_tokens' => 'lots'])) + ->toThrow(ConfigurationException::class, 'Setting "max_tokens" of provider "fake" must be an integer, string given.'); + expect(fn () => $this->factory->create(['api_key' => ['k']])) + ->toThrow(ConfigurationException::class, 'Setting "api_key" of provider "fake" must be a string, array given.'); + }); + + it('refuses an effort it does not recognise, listing the ones it does', function () { + expect(fn () => $this->factory->create(['api_key' => 'k', 'effort' => 'enormous'])) + ->toThrow(ConfigurationException::class, 'Setting "effort" of provider "fake" must be one of "none", "minimal", "low", "medium", "high", "extra-high", "maximum"; "enormous" given.'); + }); + + it('accepts an Effort as well as its name', function () { + expect($this->factory->create(['api_key' => 'k', 'effort' => Effort::Low])->effort)->toBe(Effort::Low); + }); + + it('refuses to read a string that was never given and has no default', function () { + expect(fn () => (new SettingValues('fake', []))->string('endpoint')) + ->toThrow(ConfigurationException::class, 'Provider "fake" needs the "endpoint" setting.'); + }); + + it('throws an InvalidArgumentException, which callers already catch around construction', function () { + expect(new ConfigurationException('x'))->toBeInstanceOf(InvalidArgumentException::class); + }); +}); diff --git a/tests/Unit/ProviderRegistryTest.php b/tests/Unit/ProviderRegistryTest.php new file mode 100644 index 0000000..6c05c03 --- /dev/null +++ b/tests/Unit/ProviderRegistryTest.php @@ -0,0 +1,58 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +use PapiAI\Core\Exception\ConfigurationException; +use PapiAI\Core\Factory\ProviderRegistry; +use PapiAI\Core\Tests\Fixtures\FakeProvider; +use PapiAI\Core\Tests\Fixtures\FakeProviderFactory; + +describe('The provider registry', function () { + it('lists the factories it was given', function () { + $fake = new FakeProviderFactory(); + $other = new FakeProviderFactory('other', 'acme/other'); + + expect((new ProviderRegistry([$fake, $other]))->installed())->toBe([$fake, $other]); + }); + + it('creates a provider through the factory of that name', function () { + $registry = new ProviderRegistry([new FakeProviderFactory('other', 'acme/other'), new FakeProviderFactory()]); + + expect($registry->create('fake', ['api_key' => 'k']))->toBeInstanceOf(FakeProvider::class); + }); + + it('takes any iterable, a discovery included', function () { + $registry = new ProviderRegistry((function () { + yield new FakeProviderFactory(); + })()); + + expect($registry->installed())->toHaveCount(1); + }); + + it('names what is installed when asked for something that is not', function () { + $registry = new ProviderRegistry([new FakeProviderFactory(), new FakeProviderFactory('other', 'acme/other')]); + + expect(fn () => $registry->create('google', [])) + ->toThrow(ConfigurationException::class, 'Provider "google" is not installed. Installed: "fake", "other".'); + }); + + it('says when no provider is installed at all', function () { + expect(fn () => (new ProviderRegistry([]))->create('google', [])) + ->toThrow(ConfigurationException::class, 'Provider "google" is not installed, and no papi provider package is.'); + }); + + it('refuses two packages claiming the same name', function () { + expect(fn () => new ProviderRegistry([new FakeProviderFactory(), new FakeProviderFactory('fake', 'acme/fake')])) + ->toThrow(ConfigurationException::class, 'Both "papi-ai/fake" and "acme/fake" provide "fake".'); + }); +}); diff --git a/tests/Unit/StopReasonTest.php b/tests/Unit/StopReasonTest.php new file mode 100644 index 0000000..cea756b --- /dev/null +++ b/tests/Unit/StopReasonTest.php @@ -0,0 +1,110 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +use PapiAI\Core\Agent; +use PapiAI\Core\Contracts\ProviderInterface; +use PapiAI\Core\Response; +use PapiAI\Core\StopReason; +use PapiAI\Core\ToolCall; + +describe('Why a response stopped', function () { + it('is Other when the provider does not say', function () { + expect((new Response('hi'))->stoppedBecause)->toBe(StopReason::Other); + }); + + it('reports truncation only when the output ceiling cut the answer short', function () { + expect((new Response('hi', stoppedBecause: StopReason::MaxTokens))->isTruncated())->toBeTrue(); + expect((new Response('hi', stoppedBecause: StopReason::Stop))->isTruncated())->toBeFalse(); + }); + + it('survives copying, with data or with new messages', function () { + $response = new Response('hi', stopReason: 'length', stoppedBecause: StopReason::MaxTokens); + + foreach ([$response->withData(['a' => 1]), $response->withMessages([])] as $copy) { + expect($copy->stoppedBecause)->toBe(StopReason::MaxTokens); + expect($copy->stopReason)->toBe('length'); + } + }); + + it('replaces only the messages when copied with new ones', function () { + $copy = (new Response('hi', data: ['a' => 1]))->withMessages(['history']); + + expect($copy->messages)->toBe(['history']); + expect($copy->data)->toBe(['a' => 1]); + expect($copy->text)->toBe('hi'); + }); + + it('normalises the Chat Completions finish reasons', function () { + $reasons = [ + 'stop' => StopReason::Stop, + 'length' => StopReason::MaxTokens, + 'model_length' => StopReason::MaxTokens, + 'tool_calls' => StopReason::ToolCalls, + 'function_call' => StopReason::ToolCalls, + 'content_filter' => StopReason::Refused, + 'insufficient_system_resource' => StopReason::Other, + ]; + + foreach ($reasons as $raw => $expected) { + $response = Response::fromOpenAI(['choices' => [['message' => ['content' => 'x'], 'finish_reason' => $raw]]]); + + expect($response->stoppedBecause)->toBe($expected, $raw); + expect($response->stopReason)->toBe($raw); + } + }); + + it('calls a turn with tool calls tool_calls, whatever finish reason came with it', function () { + $response = Response::fromOpenAI(['choices' => [[ + 'message' => ['content' => null, 'tool_calls' => [['id' => 'c1', 'type' => 'function', 'function' => ['name' => 'f', 'arguments' => '{}']]]], + 'finish_reason' => 'stop', + ]]]); + + expect($response->stoppedBecause)->toBe(StopReason::ToolCalls); + }); + + it('normalises the Anthropic stop reasons', function () { + $reasons = [ + 'end_turn' => StopReason::Stop, + 'stop_sequence' => StopReason::Stop, + 'max_tokens' => StopReason::MaxTokens, + 'model_context_window_exceeded' => StopReason::MaxTokens, + 'tool_use' => StopReason::ToolCalls, + 'refusal' => StopReason::Refused, + 'pause_turn' => StopReason::Other, + ]; + + foreach ($reasons as $raw => $expected) { + expect(Response::fromAnthropic(['content' => [], 'stop_reason' => $raw])->stoppedBecause)->toBe($expected, $raw); + } + }); + + it('keeps the provider\'s stop reason through an agent run, structured or not', function () { + $provider = Mockery::mock(ProviderInterface::class); + $provider->shouldReceive('chat')->andReturn(new Response('{"a": 1}', stopReason: 'length', stoppedBecause: StopReason::MaxTokens)); + $provider->shouldReceive('supportsStructuredOutput')->andReturn(true); + $agent = new Agent(provider: $provider, model: 'test-model'); + + expect($agent->run('hi')->stoppedBecause)->toBe(StopReason::MaxTokens); + expect($agent->run('hi', ['outputSchema' => PapiAI\Core\Schema\Schema::object(['a' => PapiAI\Core\Schema\Schema::integer()])])->stoppedBecause) + ->toBe(StopReason::MaxTokens); + + Mockery::close(); + }); + + it('never reports a turn with tool calls as truncated', function () { + $response = new Response('', toolCalls: [new ToolCall('c1', 'f', [])], stoppedBecause: StopReason::ToolCalls); + + expect($response->isTruncated())->toBeFalse(); + }); +});