MaybeLogMessage($message); $url = "https://api.deepseek.com/v1/chat/completions"; if($apiKey == '') $apiKey = $this->GetAPIKey(); // Make the API request using WordPress HTTP API $response = \wp_remote_post($url, [ 'headers' => [ 'Authorization' => 'Bearer ' . $apiKey, 'Content-Type' => 'application/json', ], 'body' => json_encode( [ "model" => "deepseek-chat", 'temperature' => 0.5, "messages" => $message, "max_tokens" => 8000, 'response_format' => [ 'type' => 'json_object' ] ]), 'timeout' => 60 ]); // Check if the request failed if (is_wp_error($response)) { throw new FriendlyException($response->get_error_message()); } // Get HTTP response code $httpCode = wp_remote_retrieve_response_code($response); $body = wp_remote_retrieve_body($response); $decodedBody = json_decode($body, true); // Convert JSON response to array // If the API returns an error message, use it $errorMessage = Sanitizer::GetStringValueFromPath($decodedBody, ['error', 'message'], 'Invalid API Key'); // Check if API Key is valid (DeepSeek should return 200 for valid keys) if ($httpCode !== 200) { throw new FriendlyException("The api key does not seems to be a valid DeepSeek api key error: " . $errorMessage); } $choices = Sanitizer::GetValueFromPath($decodedBody, ['choices'], null); if($choices == null) throw new FriendlyException("There was no response, please try again"); $content = $choices[0]['message']['content']; $usageMetadata = Sanitizer::GetValueFromPath($decodedBody, ['usage'], null); $inputTokenCount = $usageMetadata->prompt_tokens ?? 0; // Input tokens $outputTokenCount = $usageMetadata->completion_tokens ?? 0; // Output tokens $totalTokenCount = $usageMetadata->total_tokens ?? 0; // Total tokens LogManager::LogDebug("DeepSeek Response:\r\n" . $content); LogManager::LogDebug($this->GetModelName() . ' Usage: Input Tokens: ' . $inputTokenCount . ' Output Tokens: ' . $outputTokenCount . ' Total Tokens: ' . $totalTokenCount); LogManager::LogDebug("DeepSeek Response:\r\n" . $content); return $content; } public function GetModelName() { return 'deepseek'; } }