$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, ); } }