Passed
Pull Request — 1.11.x (#6041)
by Yannick
09:04
created

DeepSeek::sendRequest()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 26
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 15
dl 0
loc 26
rs 9.7666
c 1
b 0
f 0
cc 4
nc 3
nop 3
1
<?php
2
/* For license terms, see /license.txt */
3
4
require_once 'Url.php';
5
6
class DeepSeek
7
{
8
    private $apiKey;
9
    private $headers;
10
11
    public function __construct(string $apiKey)
12
    {
13
        $this->apiKey = $apiKey;
14
        $this->headers = [
15
            'Content-Type: application/json',
16
            "Authorization: Bearer {$this->apiKey}",
17
        ];
18
    }
19
20
    /**
21
     * Generate questions using the DeepSeek API.
22
     *
23
     * @param array $payload Data to send to the API
24
     * @return string Decoded response from the API
25
     * @throws Exception If an error occurs during the request
26
     */
27
    public function generateQuestions(array $payload): string
28
    {
29
        $url = Url::completionsUrl();
30
        $response = $this->sendRequest($url, 'POST', $payload);
31
32
        if (empty($response)) {
33
            throw new Exception('The DeepSeek API returned no response.');
34
        }
35
36
        $result = json_decode($response, true);
37
38
        // Validate errors returned by the API
39
        if (isset($result['error'])) {
40
            throw new Exception("DeepSeek API Error: {$result['error']['message']}");
41
        }
42
43
        // Ensure the response contains the expected "choices" field
44
        if (!isset($result['choices'][0]['message']['content'])) {
45
            throw new Exception('Unexpected response format from the DeepSeek API.');
46
        }
47
48
        return $result['choices'][0]['message']['content'];
49
    }
50
51
    /**
52
     * Send a request to the DeepSeek API.
53
     *
54
     * @param string $url Endpoint to send the request to
55
     * @param string $method HTTP method (e.g., GET, POST)
56
     * @param array $data Data to send as JSON
57
     * @return string Raw response from the API
58
     * @throws Exception If a cURL error occurs
59
     */
60
    private function sendRequest(string $url, string $method, array $data = []): string
61
    {
62
        $ch = curl_init($url);
63
64
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
65
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
66
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
67
        curl_setopt($ch, CURLOPT_HTTPHEADER, $this->headers);
68
69
        $response = curl_exec($ch);
70
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
71
72
        if (curl_errno($ch)) {
73
            $errorMessage = curl_error($ch);
74
            curl_close($ch);
75
            throw new Exception("cURL Error: {$errorMessage}");
76
        }
77
78
        curl_close($ch);
79
80
        // Validate HTTP status codes
81
        if ($httpCode < 200 || $httpCode >= 300) {
82
            throw new Exception("Request to DeepSeek failed with HTTP status code: {$httpCode}");
83
        }
84
85
        return $response;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $response could return the type true which is incompatible with the type-hinted return string. Consider adding an additional type-check to rule them out.
Loading history...
86
    }
87
}
88