api_key = $api_key; $this->idempotency_context = $idempotency_context; $this->workspace_id = $workspace_id; $this->initializeModels(); } /** * Initialize available Claude models with their configurations. * * @return void */ private function initializeModels(): void { $this->models = []; foreach ( ModelCatalog::get_models( 'claude' ) as $model ) { $capabilities = ModelCatalog::get_capabilities( 'claude', $model ); $this->models[ $model ] = [ 'name' => $model, 'max_tokens' => 8192, 'temperature' => 0.7, 'has_temperature' => ! empty( $capabilities['supports_temperature'] ), 'supports_system' => true, 'structured_output' => $capabilities['structured_output'] ?? 'tool_use', 'thinking_off' => $capabilities['thinking_off'] ?? null, ]; } } /** * Set parameters for all models. * * @param array $parameters Parameters to set. * @return void */ public function setParameters( array $parameters ): void { if ( empty( $parameters ) ) { return; } try { foreach ( $this->models as $model_id => &$model_config ) { if ( isset( $parameters['temperature'] ) && is_numeric( $parameters['temperature'] ) ) { $temperature = floatval( $parameters['temperature'] ); if ( $temperature >= 0.0 && $temperature <= 1.0 && ! empty( $model_config['has_temperature'] ) ) { $model_config['temperature'] = $temperature; } } } unset( $model_config ); } catch ( \Exception $e ) { } catch ( \Error $e ) { } } /** * Get model configuration. * * @param string $model Model identifier. * @return array Model configuration or default. */ private function getModelConfig( string $model ): array { if ( ! isset( $this->models[ $model ] ) ) { throw new ProviderCallException( 'Invalid model selected: ' . esc_html( $model ), ProviderCallException::MODEL_NOT_FOUND, null, '', null, 'claude' ); } return $this->models[ $model ]; } /** * The requested model, else the catalog's Claude default. * * @param string|null $model Requested model ID. * @return string */ private function resolveModel( ?string $model ): string { return ( null !== $model && '' !== $model ) ? $model : ModelCatalog::get_default_model( 'claude' ); } /** * Turn the model's own thinking off, in the form the model accepts * (ModelCatalog's thinking_off capability): product copy gains nothing * from it and every thinking token is billed. * * @param array $body Request body. * @param array $model_config Model configuration. * @return array Request body with the thinking fields added. */ private function withThinkingOff( array $body, array $model_config ): array { $form = $model_config['thinking_off'] ?? null; if ( 'disabled' === $form || 'between_tools' === $form ) { $body['thinking'] = [ 'type' => $form ]; } elseif ( 'low_effort' === $form ) { $body['thinking'] = [ 'type' => 'adaptive' ]; $body['output_config']['effort'] = 'low'; } return $body; } /** * Sanitize prompt content. * * Outbound prompt text, not AI output: cleanOutboundPrompt() skips * cleanContent()'s "repair unclosed markdown" step, which otherwise * deletes a prompt's own literal ** / * characters (e.g. an * anti-markdown rule) before the model ever sees them. * * @param string $content Content to sanitize. * @return string Sanitized content. */ private function sanitize_prompt_content( string $content ): string { return PromptFormatter::cleanOutboundPrompt( $content ); } /** * Generate description content using Claude API. * * @param string $system_prompt System instructions. * @param string $user_prompt User message/prompt. * @param string $model Model to use. * @param int|null $maximum_length Retained for interface compatibility; no longer * used as an API token cap (length is prompt-controlled). * @return string Generated content or error message. */ public function generate_description( string $system_prompt, string $user_prompt, string $model = '', ?int $maximum_length = null ): string { $model = $this->resolveModel( $model ); $model_config = $this->getModelConfig( $model ); $body = [ 'model' => $model, 'max_tokens' => (int) $model_config['max_tokens'], 'messages' => [ [ 'role' => 'user', 'content' => $this->sanitize_prompt_content( $user_prompt ), ], ], ]; if ( ! empty( $system_prompt ) && $model_config['supports_system'] ) { $body['system'] = $this->sanitize_prompt_content( $system_prompt ); } if ( ! empty( $model_config['has_temperature'] ) ) { $body['temperature'] = $model_config['temperature']; } $body = $this->withThinkingOff( $body, $model_config ); $response = wp_remote_post( $this->api_url, [ 'headers' => $this->withProviderHeaders( [ 'Content-Type' => 'application/json', 'x-api-key' => $this->api_key, 'anthropic-version' => $this->anthropic_version, ] ), 'body' => $this->encodeBody( $body ), 'timeout' => 120, ] ); return $this->handle_response( $response, 'description', $model ); } /** * Generate FAQ content using Claude API. * * @param string $system_prompt System instructions. * @param string $user_prompt User message/prompt. * @param string|null $model Model to use. * @return string Generated content or error message. */ public function generate_from_vision( string $system_prompt, string $user_prompt, string $image_url, ?string $model = null ): string { $resolved_model = $this->resolveModel( $model ); $ai_gate = \AIPT\Core\Services\AiSupportGate::guard(); if ( $ai_gate instanceof \WP_Error ) { throw ProviderCallException::aiDisabled( $ai_gate, 'claude' ); } try { $encoded_image = VisionImageEncoder::fetchAndEncode( $image_url ); } catch ( \RuntimeException $e ) { $detailed_error = ErrorHandler::format_api_response_error( [ 'code' => 'aipt_vision_fetch_failed', 'message' => esc_html( $e->getMessage() ), 'type' => 'vision_image_fetch_failed', ], 'Claude', 0 ); throw new ProviderCallException( $detailed_error, ProviderCallException::IMAGE_UNAVAILABLE, null, 'vision_image_fetch_failed', null, 'claude', $e ); } $model_config = $this->getModelConfig( $resolved_model ); $body = [ 'model' => $resolved_model, 'max_tokens' => (int) $model_config['max_tokens'], 'messages' => [ [ 'role' => 'user', 'content' => [ [ 'type' => 'image', 'source' => [ 'type' => 'base64', 'media_type' => $encoded_image['mime_type'], 'data' => $encoded_image['data'], ], ], [ 'type' => 'text', 'text' => $this->sanitize_prompt_content( $user_prompt ), ], ], ], ], ]; if ( ! empty( $system_prompt ) && $model_config['supports_system'] ) { $body['system'] = $this->sanitize_prompt_content( $system_prompt ); } if ( ! empty( $model_config['has_temperature'] ) ) { $body['temperature'] = (float) $model_config['temperature']; } $body = $this->withThinkingOff( $body, $model_config ); $response = wp_remote_post( $this->api_url, [ 'headers' => $this->withProviderHeaders( [ 'Content-Type' => 'application/json', 'x-api-key' => $this->api_key, 'anthropic-version' => $this->anthropic_version, ] ), 'body' => $this->encodeBody( $body ), 'timeout' => 60, ] ); return $this->handle_response( $response, 'vision', $resolved_model ); } public function generate_faq_content( string $system_prompt, string $user_prompt, ?string $model = null ): string { $model = $this->resolveModel( $model ); $model_config = $this->getModelConfig( $model ); $body = [ 'model' => $model, 'max_tokens' => (int) $model_config['max_tokens'], 'messages' => [ [ 'role' => 'user', 'content' => $this->sanitize_prompt_content( $user_prompt ), ], ], ]; if ( ! empty( $system_prompt ) && $model_config['supports_system'] ) { $body['system'] = $this->sanitize_prompt_content( $system_prompt ); } if ( ! empty( $model_config['has_temperature'] ) ) { $body['temperature'] = $model_config['temperature']; } $body = $this->withThinkingOff( $body, $model_config ); $response = wp_remote_post( $this->api_url, [ 'headers' => $this->withProviderHeaders( [ 'Content-Type' => 'application/json', 'x-api-key' => $this->api_key, 'anthropic-version' => $this->anthropic_version, ] ), 'body' => $this->encodeBody( $body ), 'timeout' => 120, ] ); return $this->handle_response( $response, 'faq', $model ); } /** * Generate a structured (JSON-schema-shaped) answer. * * Additive method for StructuredOutputClientInterface. When * $options['native'] is true this forces a single tool call * (`tool_choice: { type: 'tool' }`) whose `input_schema` is * $json_schema and reads the already-parsed object out of the * `tool_use` content block; a model that rejects a forced tool call * gets $json_schema as its answer format (`output_config.format`) and * its JSON text is decoded instead. Otherwise it sends a plain prompt * call (the caller has already appended the JSON instruction to * $user_prompt) and returns `decoded: null`. Does not change * generate_description()'s request body or behavior. * * @param string $system_prompt System instructions. * @param string $user_prompt User message/prompt. * @param array $json_schema JSON schema of the expected answer. * @param string $model Model ID ('' = default). * @param array $options See StructuredOutputClientInterface. * @return array{raw_text: string, decoded: array|null, used_native: bool, model: string} */ public function generate_structured( string $system_prompt, string $user_prompt, array $json_schema, string $model = '', array $options = array() ): array { $resolved_model = $this->resolveModel( $model ); $model_config = $this->getModelConfig( $resolved_model ); $native = ! empty( $options['native'] ); $schema_name = $this->sanitize_schema_name( $options['schema_name'] ?? '' ); $content = $this->sanitize_prompt_content( $user_prompt ); if ( ! empty( $options['image']['url'] ) ) { $content = $this->build_vision_content( $content, (string) $options['image']['url'] ); } $max_tokens = isset( $options['max_tokens'] ) ? (int) $options['max_tokens'] : 0; if ( $max_tokens <= 0 ) { $max_tokens = (int) $model_config['max_tokens']; } $body = [ 'model' => $resolved_model, 'max_tokens' => $max_tokens, 'messages' => [ [ 'role' => 'user', 'content' => $content, ], ], ]; if ( ! empty( $system_prompt ) && $model_config['supports_system'] ) { $body['system'] = $this->sanitize_prompt_content( $system_prompt ); } if ( ! empty( $model_config['has_temperature'] ) ) { $body['temperature'] = $model_config['temperature']; } $json_format = $native && 'json_schema' === $model_config['structured_output']; $forced_tool = $native && ! $json_format; if ( $json_format ) { $body['output_config']['format'] = [ 'type' => 'json_schema', 'schema' => $json_schema, ]; } elseif ( $forced_tool ) { $body['tools'] = [ [ 'name' => $schema_name, 'description' => 'Return the structured answer for this request.', 'input_schema' => $json_schema, ], ]; $body['tool_choice'] = [ 'type' => 'tool', 'name' => $schema_name, ]; } $timeout = isset( $options['timeout'] ) && (int) $options['timeout'] > 0 ? (int) $options['timeout'] : 120; $body = $this->withThinkingOff( $body, $model_config ); $response = wp_remote_post( $this->api_url, [ 'headers' => $this->withProviderHeaders( [ 'Content-Type' => 'application/json', 'x-api-key' => $this->api_key, 'anthropic-version' => $this->anthropic_version, ] ), 'body' => $this->encodeBody( $body ), 'timeout' => $timeout, ] ); return $this->handle_structured_response( $response, $resolved_model, $forced_tool, $schema_name, $json_format ); } /** * Handle an API response for generate_structured(), extracting either * the forced tool_use input (native) or the plain text block. * * Mirrors handle_response()'s error-handling branches exactly; only the * success-path extraction differs. * * @param array|\WP_Error $response API response. * @param string $model Model identifier (for usage tracking). * @param bool $native Whether a forced tool call was requested. * @param string $tool_name Forced tool name, when $native is true. * @param bool $json_format Whether the schema was sent as the answer format, so the text block is the JSON answer. * @return array{raw_text: string, decoded: array|null, used_native: bool, model: string} */ private function handle_structured_response( $response, string $model, bool $native, string $tool_name, bool $json_format = false ): array { if ( is_wp_error( $response ) ) { $error_message = $response->get_error_message(); $detailed_error = ErrorHandler::format_api_response_error( $error_message, 'claude', 0 ); throw new ProviderCallException( $detailed_error, ProviderCallException::transportReason( $response ), null, '', null, 'claude' ); } $response_code = (int) wp_remote_retrieve_response_code( $response ); $content_type = (string) wp_remote_retrieve_header( $response, 'content-type' ); $body_str = (string) wp_remote_retrieve_body( $response ); self::throwIfHtmlBody( $content_type, $body_str, $response_code ); $body = json_decode( $body_str, true ); if ( ! is_array( $body ) ) { $body = []; } if ( $response_code !== 200 ) { if ( isset( $body['request_id'] ) && is_string( $body['request_id'] ) ) { ErrorHandler::log_error( sprintf( 'Claude request_id=%s status=%d', sanitize_text_field( $body['request_id'] ), $response_code ), 'debug' ); } $retry_after_header = ErrorHandler::parse_retry_after_header( wp_remote_retrieve_header( $response, 'retry-after' ) ); $error_payload = $this->parse_error_response( $body, $response_code ); $detailed_error = ErrorHandler::format_api_response_error( $error_payload, 'claude', $response_code ); throw self::providerErrorFromResponse( $error_payload, $response_code, $detailed_error, $retry_after_header ); } $content_blocks = is_array( $body['content'] ?? null ) ? $body['content'] : []; $stop_reason = isset( $body['stop_reason'] ) && is_string( $body['stop_reason'] ) ? $body['stop_reason'] : ''; self::throwIfRefused( $stop_reason, $response_code ); if ( $native ) { self::throwIfNativeAnswerWasCutOff( $stop_reason, $response_code ); foreach ( $content_blocks as $block ) { if ( is_array( $block ) && 'tool_use' === ( $block['type'] ?? '' ) && ( $block['name'] ?? '' ) === $tool_name && is_array( $block['input'] ?? null ) ) { \AIPT\Core\Services\UsageTracker::trackApiCall( 'claude', (string) ( $body['model'] ?? $model ), (int) ( $body['usage']['input_tokens'] ?? 0 ), (int) ( $body['usage']['output_tokens'] ?? 0 ) ); return [ 'raw_text' => (string) wp_json_encode( $block['input'] ), 'decoded' => $block['input'], 'used_native' => true, 'model' => $model, ]; } } } foreach ( $content_blocks as $block ) { if ( is_array( $block ) && 'text' === ( $block['type'] ?? '' ) && isset( $block['text'] ) && '' !== trim( (string) $block['text'] ) ) { self::throwIfTruncatedAndUndecodable( $stop_reason, (string) $block['text'], $response_code ); \AIPT\Core\Services\UsageTracker::trackApiCall( 'claude', (string) ( $body['model'] ?? $model ), (int) ( $body['usage']['input_tokens'] ?? 0 ), (int) ( $body['usage']['output_tokens'] ?? 0 ) ); $decoded = $json_format ? json_decode( (string) $block['text'], true ) : null; return [ 'raw_text' => (string) $block['text'], 'decoded' => is_array( $decoded ) ? $decoded : null, 'used_native' => is_array( $decoded ), 'model' => $model, ]; } } $detailed_error = ErrorHandler::format_api_response_error( __( 'Unexpected response format from Claude API', 'ai-product-tools' ), 'claude', 0 ); throw new ProviderCallException( $detailed_error, self::classifyEmptyContentReason( $stop_reason ), $response_code, $stop_reason, null, 'claude' ); } /** * Build an Anthropic-shaped multi-part user content array carrying the * image block before the text block, reusing the same fetch/encode path * as generate_from_vision(). * * @param string $text User prompt text. * @param string $image_url Image URL or data URI. * @return array */ private function build_vision_content( string $text, string $image_url ): array { try { $encoded_image = VisionImageEncoder::fetchAndEncode( $image_url ); } catch ( \RuntimeException $e ) { $detailed_error = ErrorHandler::format_api_response_error( [ 'code' => 'aipt_vision_fetch_failed', 'message' => esc_html( $e->getMessage() ), 'type' => 'vision_image_fetch_failed', ], 'Claude', 0 ); throw new ProviderCallException( $detailed_error, ProviderCallException::IMAGE_UNAVAILABLE, null, 'vision_image_fetch_failed', null, 'claude', $e ); } return [ [ 'type' => 'image', 'source' => [ 'type' => 'base64', 'media_type' => $encoded_image['mime_type'], 'data' => $encoded_image['data'], ], ], [ 'type' => 'text', 'text' => $text, ], ]; } /** * Sanitize a caller-supplied schema name to Anthropic's allowed tool-name * charset. * * @param mixed $name Raw schema name. * @return string */ private function sanitize_schema_name( $name ): string { $name = is_string( $name ) ? trim( $name ) : ''; $name = (string) preg_replace( '/[^A-Za-z0-9_-]/', '_', $name ); $name = substr( $name, 0, 64 ); return '' !== $name ? $name : 'aipt_blueprint_schema'; } /** * Encode a request body to JSON, failing loudly on invalid UTF-8. * * Mirrors the OpenRouter/OpenAI clients: wp_json_encode() returns false when * the payload contains invalid byte sequences. Passing that false straight * to wp_remote_post() would silently dispatch an empty body and surface an * opaque provider error instead of a clear local one. * * @param array $body Request body. * @return string Encoded JSON. * @throws ProviderCallException When encoding fails. */ private function encodeBody( array $body ): string { $json = wp_json_encode( $body ); if ( false === $json ) { throw new ProviderCallException( esc_html__( 'Failed to encode Claude request body as JSON. The product data may contain invalid characters.', 'ai-product-tools' ), ProviderCallException::BAD_REQUEST, null, '', null, 'claude' ); } return $json; } /** * Handle API response. * * @param array|\WP_Error $response API response. * @param string $content_type Type of content being generated. * @param string $model Model identifier (for usage tracking). * @return string Extracted content or error message. */ private function handle_response( $response, string $content_type, string $model = '' ): string { if ( is_wp_error( $response ) ) { $error_message = $response->get_error_message(); $detailed_error = ErrorHandler::format_api_response_error( $error_message, 'claude', 0 ); throw new ProviderCallException( $detailed_error, ProviderCallException::transportReason( $response ), null, '', null, 'claude' ); } $response_code = (int) wp_remote_retrieve_response_code( $response ); $response_content_type = (string) wp_remote_retrieve_header( $response, 'content-type' ); $body_str = (string) wp_remote_retrieve_body( $response ); self::throwIfHtmlBody( $response_content_type, $body_str, $response_code ); $body = json_decode( $body_str, true ); if ( ! is_array( $body ) ) { $body = []; } if ( $response_code !== 200 ) { if ( isset( $body['request_id'] ) && is_string( $body['request_id'] ) ) { ErrorHandler::log_error( sprintf( 'Claude request_id=%s status=%d', sanitize_text_field( $body['request_id'] ), $response_code ), 'debug' ); } $retry_after_header = ErrorHandler::parse_retry_after_header( wp_remote_retrieve_header( $response, 'retry-after' ) ); $error_payload = $this->parse_error_response( $body, $response_code ); $detailed_error = ErrorHandler::format_api_response_error( $error_payload, 'claude', $response_code ); throw self::providerErrorFromResponse( $error_payload, $response_code, $detailed_error, $retry_after_header ); } $text_value = null; $content_blocks = is_array( $body['content'] ?? null ) ? $body['content'] : []; foreach ( $content_blocks as $block ) { if ( is_array( $block ) && 'text' === ( $block['type'] ?? '' ) && isset( $block['text'] ) && '' !== trim( (string) $block['text'] ) ) { $text_value = (string) $block['text']; break; } } $stop_reason = isset( $body['stop_reason'] ) && is_string( $body['stop_reason'] ) ? $body['stop_reason'] : ''; if ( null !== $text_value ) { self::throwIfNonEmptyTextWasCutOff( $stop_reason, $response_code ); \AIPT\Core\Services\UsageTracker::trackApiCall( 'claude', (string) ( $body['model'] ?? $model ), (int) ( $body['usage']['input_tokens'] ?? 0 ), (int) ( $body['usage']['output_tokens'] ?? 0 ) ); return $text_value; } $detailed_error = ErrorHandler::format_api_response_error( __( 'Unexpected response format from Claude API', 'ai-product-tools' ), 'claude', 0 ); throw new ProviderCallException( $detailed_error, self::classifyEmptyContentReason( $stop_reason ), $response_code, $stop_reason, null, 'claude' ); } /** * Build a ProviderCallException from a parsed Claude error payload, * classifying its reason from the HTTP status plus Anthropic's own * `error.type` when a structured error body was present. * * @param array|string $error_payload Return value of parse_error_response(). * @param int $response_code HTTP status code. * @param string $detailed_error Already-formatted technical message (unchanged `getMessage()`). * @return ProviderCallException */ private static function providerErrorFromResponse( $error_payload, int $response_code, string $detailed_error, ?int $retry_after_header = null ): ProviderCallException { $has_envelope = is_array( $error_payload ); $type = $has_envelope && isset( $error_payload['type'] ) && is_string( $error_payload['type'] ) ? $error_payload['type'] : ''; $message = $has_envelope && isset( $error_payload['message'] ) && is_string( $error_payload['message'] ) ? $error_payload['message'] : ( is_string( $error_payload ) ? $error_payload : '' ); return new ProviderCallException( $detailed_error, self::classifyErrorReason( $response_code, $type, $message, $has_envelope ), $response_code, $type, $retry_after_header ?? ErrorHandler::extract_retry_after( $error_payload ), 'claude' ); } /** * Classify a Claude error response into a stable ProviderCallException reason. * * @param int $response_code HTTP status code. * @param string $type Anthropic `error.type`, e.g. "overloaded_error", "rate_limit_error". * @param string $message `error.message` (or the hardcoded status-map string), used to tell an * exhausted credit balance and a schema-shaped 400 apart from a plain one. * @param bool $has_envelope Whether the body actually parsed as Anthropic's own * {type:"error", error:{...}} shape (set by providerErrorFromResponse()). * @return string */ private static function classifyErrorReason( int $response_code, string $type, string $message, bool $has_envelope = true ): string { if ( ! $has_envelope ) { if ( $response_code >= 500 ) { return ProviderCallException::PROVIDER_UNAVAILABLE; } if ( 429 === $response_code ) { return ProviderCallException::RATE_LIMITED; } return ProviderCallException::NETWORK_ERROR; } if ( 'authentication_error' === $type || 401 === $response_code ) { return ProviderCallException::AUTH_INVALID_KEY; } if ( 'permission_error' === $type || 403 === $response_code ) { return ProviderCallException::AUTH_FORBIDDEN; } if ( 'not_found_error' === $type || 404 === $response_code ) { return ProviderCallException::MODEL_NOT_FOUND; } if ( 529 === $response_code || 'overloaded_error' === $type ) { return ProviderCallException::PROVIDER_UNAVAILABLE; } if ( 'rate_limit_error' === $type || 429 === $response_code ) { return ProviderCallException::RATE_LIMITED; } if ( 413 === $response_code || 'request_too_large' === $type ) { return ProviderCallException::REQUEST_TOO_LARGE; } if ( 'invalid_request_error' === $type || 400 === $response_code ) { if ( false !== stripos( $message, 'credit balance' ) ) { return ProviderCallException::QUOTA_EXHAUSTED; } if ( false !== stripos( $message, 'anthropic-workspace-id' ) ) { return ProviderCallException::WORKSPACE_REQUIRED; } $looks_like_schema = false !== stripos( $message, 'tool_choice' ) || false !== stripos( $message, 'input_schema' ) || false !== stripos( $message, 'tools.' ) || false !== stripos( $message, 'output_config.format' ) || false !== stripos( $message, 'schema' ); return $looks_like_schema ? ProviderCallException::INVALID_SCHEMA_REQUEST : ProviderCallException::BAD_REQUEST; } if ( $response_code >= 500 || 'api_error' === $type ) { return ProviderCallException::PROVIDER_UNAVAILABLE; } return ProviderCallException::BAD_REQUEST; } /** * A security plugin or hosting firewall that intercepts the call answers * with an HTML page instead of Anthropic's JSON. Checked unconditionally, * before any status-based classification, exactly like the other three * clients' throwIfHtmlBody(). * * @param string $content_type Response content-type header. * @param string $body_str Raw response body. * @param int $response_code HTTP status code. * @throws ProviderCallException When the body is an HTML page. */ private static function throwIfHtmlBody( string $content_type, string $body_str, int $response_code ): void { if ( ! ErrorHandler::looks_like_html_body( $content_type, $body_str ) ) { return; } throw new ProviderCallException( __( 'The API response was not valid JSON. This is often caused by a server firewall or security plugin blocking outbound requests. Please contact your hosting provider or check your security plugin settings.', 'ai-product-tools' ), ProviderCallException::NETWORK_ERROR, $response_code, '', null, 'claude' ); } /** * A non-empty answer can still be a cutoff rather than a complete success: * `stop_reason` describes how generation ended independent of whether any * text came back with it. * * @param string $stop_reason Claude `stop_reason`. * @param int $response_code HTTP status code. * @throws ProviderCallException When the answer was cut off mid-generation or declined. */ private static function throwIfNonEmptyTextWasCutOff( string $stop_reason, int $response_code ): void { self::throwIfRefused( $stop_reason, $response_code ); if ( 'max_tokens' !== $stop_reason ) { return; } throw new ProviderCallException( 'Invalid response from Claude API: the answer was cut off before it finished', ProviderCallException::TRUNCATED_OUTPUT, $response_code, $stop_reason, null, 'claude' ); } /** * generate_structured()'s native (forced tool_use) truncation rule: unlike * the text path, Anthropic hands back `input` already parsed into a PHP * array, so a length cutoff mid-object still satisfies `is_array()` while * being incomplete. There is no raw text left to re-decode, so this reads * `stop_reason` alone, before the native branch ever inspects a block. A * complete forced tool call always reports stop_reason 'tool_use', never * 'max_tokens', so a normal answer is unaffected. * * @param string $stop_reason Claude `stop_reason`. * @param int $response_code HTTP status code. * @throws ProviderCallException When the forced tool call was cut off by the token limit. */ private static function throwIfNativeAnswerWasCutOff( string $stop_reason, int $response_code ): void { if ( 'max_tokens' !== $stop_reason ) { return; } throw new ProviderCallException( 'Invalid response from Claude API: the answer was cut off before it finished', ProviderCallException::TRUNCATED_OUTPUT, $response_code, $stop_reason, null, 'claude' ); } /** * generate_structured()'s own truncation rule: a length cutoff only fails * the call when the text it cut off does not even decode as JSON. * * @param string $stop_reason Claude `stop_reason`. * @param string $text Raw text block content. * @param int $response_code HTTP status code. * @throws ProviderCallException When a length cutoff left undecodable JSON, or the answer was declined. */ private static function throwIfTruncatedAndUndecodable( string $stop_reason, string $text, int $response_code ): void { self::throwIfRefused( $stop_reason, $response_code ); if ( 'max_tokens' !== $stop_reason ) { return; } $maybe = json_decode( $text, true ); if ( JSON_ERROR_NONE === json_last_error() && is_array( $maybe ) ) { return; } throw new ProviderCallException( 'Invalid response from Claude API: the answer was cut off before it finished', ProviderCallException::TRUNCATED_OUTPUT, $response_code, $stop_reason, null, 'claude' ); } /** * Claude can decline part way through and still return the text it wrote * before stopping (stop_reason "refusal"); that text is never an answer. * * @param string $stop_reason Claude `stop_reason`. * @param int $response_code HTTP status code. * @throws ProviderCallException When Claude declined to finish. */ private static function throwIfRefused( string $stop_reason, int $response_code ): void { if ( 'refusal' !== $stop_reason ) { return; } throw new ProviderCallException( 'Invalid response from Claude API: the model declined to finish the answer', ProviderCallException::CONTENT_BLOCKED, $response_code, $stop_reason, null, 'claude' ); } /** * Classify why Claude's content came back empty: a safety refusal and a * length cutoff both need their own reason instead of the generic * "unexpected response format" bucket. * * @param string $stop_reason Claude `stop_reason`, e.g. "refusal", "max_tokens". * @return string */ private static function classifyEmptyContentReason( string $stop_reason ): string { if ( 'refusal' === $stop_reason ) { return ProviderCallException::CONTENT_BLOCKED; } if ( 'max_tokens' === $stop_reason ) { return ProviderCallException::TRUNCATED_OUTPUT; } return ProviderCallException::MALFORMED_RESPONSE; } /** * Parse Claude error response into a structured payload. * * When Claude returns a structured error body, the full error array is returned * so downstream ErrorHandler can surface both type and message. Falls back to a * hardcoded HTTP-status-to-message map when no structured error is present. * * @param array|null $body Response body. * @param int $response_code HTTP response code. * @return array|string Structured error array when available, mapped string otherwise. */ private function parse_error_response( ?array $body, int $response_code ) { if ( is_array( $body ) && isset( $body['error'] ) && is_array( $body['error'] ) && isset( $body['error']['message'] ) ) { $body['error']['message'] = ErrorHandler::sanitize_error_for_display( $body['error']['message'] ); return $body['error']; } $error_messages = [ 400 => __( 'Invalid request to Claude API', 'ai-product-tools' ), 401 => __( 'Invalid Claude API key', 'ai-product-tools' ), 403 => __( 'Permission denied for Claude API', 'ai-product-tools' ), 404 => __( 'Claude API endpoint not found', 'ai-product-tools' ), 429 => __( 'Claude API rate limit exceeded. Please try again later.', 'ai-product-tools' ), 500 => __( 'Claude API internal error', 'ai-product-tools' ), 529 => __( 'Claude API is temporarily overloaded. Please try again later.', 'ai-product-tools' ), ]; return $error_messages[ $response_code ] ?? sprintf( /* translators: %d: HTTP status code */ __( 'Claude API error (HTTP %d)', 'ai-product-tools' ), $response_code ); } /** * Adds every per-request Claude header beyond the base x-api-key / * anthropic-version pair: the Workspace ID header (when configured) and * the idempotency key (when applicable). Shared by every generate_* * request so a configured Workspace ID reaches the provider on generation, * vision, and structured calls alike, not only key validation. * * @param array $headers Base request headers. * @return array */ private function withProviderHeaders( array $headers ): array { if ( '' !== $this->workspace_id ) { $headers['anthropic-workspace-id'] = $this->workspace_id; } return $this->withIdempotencyHeader( $headers ); } private function withIdempotencyHeader( array $headers ): array { if ( null === $this->idempotency_context || ! $this->isIdempotencyAllowed() ) { return $headers; } $key = IdempotencyKeyContext::getIdempotencyKey(); if ( null !== $key ) { $headers['Idempotency-Key'] = $key; } return $headers; } private function isIdempotencyAllowed(): bool { $providers = \apply_filters( 'aipt_chatbot_idempotency_providers', [ 'openai', 'anthropic' ] ); if ( ! is_array( $providers ) ) { return false; } $providers = array_map( '\sanitize_key', $providers ); return in_array( 'anthropic', $providers, true ); } /** * Validate Claude API key. * * @param string $api_key API key to validate. * @param string $workspace_id Optional Workspace ID, sent as the anthropic-workspace-id header when set (required by a user-scoped key not bound to a workspace). * @return bool True if valid. * @throws \Exception If API key is invalid or validation fails. */ public static function validate_api_key( string $api_key, string $workspace_id = '' ): bool { if ( empty( $api_key ) ) { throw new ProviderCallException( __( 'Claude API key cannot be empty.', 'ai-product-tools' ), ProviderCallException::KEY_MISSING, null, '', null, 'claude' ); } if ( strpos( $api_key, 'sk-ant-' ) !== 0 ) { throw new ProviderCallException( __( 'Invalid Claude API key format. Key should start with "sk-ant-".', 'ai-product-tools' ), ProviderCallException::KEY_INVALID_FORMAT, null, '', null, 'claude' ); } $headers = [ 'x-api-key' => $api_key, 'anthropic-version' => '2023-06-01', ]; if ( '' !== $workspace_id ) { $headers['anthropic-workspace-id'] = $workspace_id; } $response = wp_remote_get( 'https://api.anthropic.com/v1/models', [ 'headers' => $headers, 'timeout' => 20, ] ); if ( is_wp_error( $response ) ) { /** @var \WP_Error $response */ $error_message = $response->get_error_message(); $detailed_error = sprintf( /* translators: %s: Error message from API request */ __( 'Claude API request failed: %s', 'ai-product-tools' ), $error_message ); throw new ProviderCallException( $detailed_error, ProviderCallException::transportReason( $response ), null, '', null, 'claude' ); } $response_code = (int) wp_remote_retrieve_response_code( $response ); $content_type = (string) wp_remote_retrieve_header( $response, 'content-type' ); $body_str = (string) wp_remote_retrieve_body( $response ); self::throwIfHtmlBody( $content_type, $body_str, $response_code ); $body = json_decode( $body_str, true ); if ( json_last_error() !== JSON_ERROR_NONE || ! is_array( $body ) ) { throw new ProviderCallException( sprintf( /* translators: %s: JSON error message */ __( 'Invalid response from Claude API: %s', 'ai-product-tools' ), json_last_error_msg() ), ProviderCallException::MALFORMED_RESPONSE, $response_code, '', null, 'claude' ); } if ( $response_code === 200 ) { return true; } if ( isset( $body['error'] ) && is_array( $body['error'] ) && isset( $body['error']['message'] ) ) { $detailed_error = ErrorHandler::format_api_response_error( $body['error'], 'claude', $response_code ); throw self::providerErrorFromResponse( $body['error'], $response_code, $detailed_error, null ); } throw new ProviderCallException( sprintf( /* translators: %d: HTTP status code */ __( 'Unexpected response from Claude API (HTTP %d).', 'ai-product-tools' ), $response_code ), $response_code >= 500 ? ProviderCallException::PROVIDER_UNAVAILABLE : ProviderCallException::MALFORMED_RESPONSE, $response_code, '', null, 'claude' ); } /** * Get available Claude models. * * @return array List of available models with their display names. */ public function get_available_models(): array { $available_models = []; foreach ( $this->models as $model_id => $config ) { $available_models[ $model_id ] = $config['name']; } return $available_models; } }