| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283 |
- <?php
-
- namespace App\Ai\Drivers;
-
- use Anthropic\Client;
- use Anthropic\Core\Exceptions\AnthropicException;
- use Anthropic\Messages\TextBlock;
- use App\Ai\AiDriver;
- use App\Ai\AiException;
- use App\Ai\AiRequest;
- use App\Ai\AiResponse;
- use Psr\Http\Client\ClientInterface;
-
- /**
- * Claude, through Anthropic's official PHP SDK.
- */
- final class ClaudeDriver implements AiDriver
- {
- /**
- * @param array<string, mixed> $config
- * @param ClientInterface|null $transporter Only set in tests, to avoid real network calls.
- */
- public function __construct(
- private readonly string $provider,
- private readonly array $config,
- private readonly ?ClientInterface $transporter = null,
- ) {}
-
- public function complete(AiRequest $request): AiResponse
- {
- $apiKey = (string) ($this->config['api_key'] ?? '');
-
- if ($apiKey === '') {
- throw new AiException('ANTHROPIC_API_KEY is missing in .env.', AiException::SETUP);
- }
-
- $options = ['timeout' => (float) config('ai.timeout', 240)];
-
- if ($this->transporter !== null) {
- $options['transporter'] = $this->transporter;
- $options['maxRetries'] = 0;
- }
-
- $client = new Client(apiKey: $apiKey, requestOptions: $options);
-
- try {
- $message = $client->messages->create(
- model: $request->model,
- maxTokens: $request->maxTokens,
- system: $request->system,
- messages: [['role' => 'user', 'content' => $request->prompt]],
- thinking: ($this->config['thinking'] ?? true) ? ['type' => 'adaptive'] : null,
- );
- } catch (AnthropicException $e) {
- throw new AiException('Claude request failed: '.$e->getMessage(), AiException::PROVIDER, $e);
- }
-
- if ($message->stopReason === 'refusal') {
- throw new AiException('Claude declined this request.', AiException::PROVIDER);
- }
-
- if ($message->stopReason === 'max_tokens') {
- throw new AiException('Claude ran out of room before finishing its answer.', AiException::INVALID_RESULT);
- }
-
- $text = '';
-
- // The answer can hold several blocks (thinking, text). Only text blocks are the answer.
- foreach ($message->content as $block) {
- if ($block instanceof TextBlock) {
- $text .= $block->text;
- }
- }
-
- return new AiResponse(
- text: $text,
- provider: $this->provider,
- model: $request->model,
- inputTokens: (int) $message->usage->inputTokens,
- outputTokens: (int) $message->usage->outputTokens,
- );
- }
- }
|