OpenAIService.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  1. <?php
  2. namespace App\Services;
  3. use Illuminate\Support\Facades\Http;
  4. use Illuminate\Support\Facades\Log;
  5. use Illuminate\Http\Client\ConnectionException;
  6. use Illuminate\Http\Client\RequestException;
  7. class OpenAIService
  8. {
  9. protected int $retries = 3;
  10. protected int $delayMs = 2000;
  11. protected string $model = 'gpt-4-1106-preview';
  12. protected string $apiUrl = 'https://api.openai.com/v1/chat/completions';
  13. protected string $apiKey;
  14. protected string $systemPrompt = '你是一个有帮助的助手。';
  15. protected float $temperature = 0.7;
  16. protected bool $stream = false;
  17. protected int $timeout = 600;
  18. protected int $maxTokens = 0;
  19. protected bool $thinking;
  20. public static function withRetry(int $retries = 3, int $delayMs = 2000): static
  21. {
  22. return (new static())->setRetry($retries, $delayMs);
  23. }
  24. public function setRetry(int $retries, int $delayMs): static
  25. {
  26. $this->retries = $retries;
  27. $this->delayMs = $delayMs;
  28. return $this;
  29. }
  30. public function setModel(string $model): static
  31. {
  32. $this->model = $model;
  33. return $this;
  34. }
  35. /**
  36. * 设置模型配置
  37. *
  38. * @param bool $thinking
  39. * @return self
  40. */
  41. public function setThinking(bool $thinking): self
  42. {
  43. $this->thinking = $thinking;
  44. return $this;
  45. }
  46. public function setApiUrl(string $url): static
  47. {
  48. $this->apiUrl = $url;
  49. return $this;
  50. }
  51. public function setApiKey(string $key): static
  52. {
  53. $this->apiKey = $key;
  54. return $this;
  55. }
  56. public function setSystemPrompt(string $prompt): static
  57. {
  58. $this->systemPrompt = $prompt;
  59. return $this;
  60. }
  61. public function setTemperature(float $temperature): static
  62. {
  63. $this->temperature = $temperature;
  64. return $this;
  65. }
  66. public function setStream(bool $stream): static
  67. {
  68. $this->stream = $stream;
  69. // 流式时需要无限超时
  70. if ($stream) {
  71. $this->timeout = 0;
  72. }
  73. return $this;
  74. }
  75. public function setMaxToken(int $maxTokens): static
  76. {
  77. $this->maxTokens = $maxTokens;
  78. return $this;
  79. }
  80. /**
  81. * 发送 GPT 请求(支持流式与非流式)
  82. */
  83. public function send(string $question): string|array
  84. {
  85. $lastException = null;
  86. for ($attempt = 1; $attempt <= $this->retries; $attempt++) {
  87. try {
  88. if ($this->stream === false) {
  89. return $this->sendNormal($question);
  90. }
  91. return $this->sendStreaming($question);
  92. } catch (RateLimitException $e) {
  93. // 429 速率限制,等待后重试
  94. $retryAfter = $e->getRetryAfter();
  95. Log::warning("请求被限流(429),等待 {$retryAfter} 秒后重试...(第 {$attempt} 次)");
  96. sleep($retryAfter);
  97. $lastException = $e;
  98. continue;
  99. } catch (ServerErrorException $e) {
  100. // 5xx 服务器错误,使用指数退避重试
  101. Log::warning("服务器错误({$e->getStatusCode()}):{$e->getMessage()},准备重试...(第 {$attempt} 次)");
  102. if ($attempt < $this->retries) {
  103. usleep($this->delayMs * 1000 * pow(2, $attempt - 1));
  104. }
  105. $lastException = $e;
  106. continue;
  107. } catch (ConnectionException $e) {
  108. // 网络连接错误,使用指数退避重试
  109. Log::warning("第 {$attempt} 次连接超时:{$e->getMessage()},准备重试...");
  110. if ($attempt < $this->retries) {
  111. usleep($this->delayMs * 1000 * pow(2, $attempt - 1));
  112. }
  113. $lastException = $e;
  114. continue;
  115. } catch (NetworkException $e) {
  116. // 其他网络错误,使用指数退避重试
  117. Log::warning("网络错误:{$e->getMessage()},准备重试...(第 {$attempt} 次)");
  118. if ($attempt < $this->retries) {
  119. usleep($this->delayMs * 1000 * pow(2, $attempt - 1));
  120. }
  121. $lastException = $e;
  122. continue;
  123. } catch (ClientErrorException $e) {
  124. // 4xx 客户端错误(除429外)不重试,直接抛出
  125. Log::error("客户端错误({$e->getStatusCode()}):{$e->getMessage()}");
  126. throw $e;
  127. } catch (\Exception $e) {
  128. // 其他未知异常,不重试,直接抛出
  129. Log::error("GPT 请求异常:" . $e->getMessage());
  130. throw $e;
  131. }
  132. }
  133. // 所有重试都失败了
  134. Log::error("请求多次失败,已重试 {$this->retries} 次");
  135. throw new \RuntimeException(
  136. '请求多次失败或超时,请稍后再试。原因: ' . ($lastException ? $lastException->getMessage() : '未知'),
  137. 504,
  138. $lastException
  139. );
  140. }
  141. /**
  142. * 普通非流式请求
  143. */
  144. protected function sendNormal(string $question): array
  145. {
  146. $data = [
  147. 'model' => $this->model,
  148. 'messages' => [
  149. ['role' => 'system', 'content' => $this->systemPrompt],
  150. ['role' => 'user', 'content' => $question],
  151. ],
  152. 'temperature' => $this->temperature,
  153. 'stream' => false,
  154. ];
  155. // setting of deepseek
  156. if (isset($this->thinking)) {
  157. $data['thinking'] = ['type' => $this->thinking ? 'enabled' : 'disabled'];
  158. }
  159. if ($this->maxTokens > 0) {
  160. $data['max_tokens'] = $this->maxTokens;
  161. }
  162. $response = Http::withToken($this->apiKey)
  163. ->timeout($this->timeout)
  164. ->post($this->apiUrl, $data);
  165. $status = $response->status();
  166. $body = $response->json();
  167. // 处理 429 速率限制
  168. if ($status === 429) {
  169. $retryAfter = (int)($response->header('Retry-After') ?? 20);
  170. throw new RateLimitException(
  171. $body['error']['message'] ?? '请求被限流',
  172. $status,
  173. $retryAfter
  174. );
  175. }
  176. // 处理 5xx 服务器错误
  177. if ($status >= 500 && $status < 600) {
  178. throw new ServerErrorException(
  179. $body['error']['message'] ?? '服务器错误',
  180. $status
  181. );
  182. }
  183. // 处理 4xx 客户端错误
  184. if ($status >= 400 && $status < 500) {
  185. throw new ClientErrorException(
  186. $body['error']['message'] ?? '客户端请求错误',
  187. $status
  188. );
  189. }
  190. // 处理成功响应
  191. if ($response->successful()) {
  192. return $body;
  193. }
  194. // 其他未知错误
  195. throw new \RuntimeException(
  196. $body['error']['message'] ?? '请求失败',
  197. $status
  198. );
  199. }
  200. /**
  201. * 流式请求(使用原生 CURL SSE)
  202. */
  203. protected function sendStreaming(string $question): string
  204. {
  205. $payload = [
  206. 'model' => $this->model,
  207. 'messages' => [
  208. ['role' => 'system', 'content' => $this->systemPrompt],
  209. ['role' => 'user', 'content' => $question],
  210. ],
  211. 'temperature' => $this->temperature,
  212. 'stream' => true,
  213. ];
  214. if ($this->maxTokens > 0) {
  215. $payload['max_tokens'] = $this->maxTokens;
  216. }
  217. $ch = curl_init($this->apiUrl);
  218. $fullContent = '';
  219. $httpCode = 0;
  220. $errorMessage = '';
  221. curl_setopt_array($ch, [
  222. CURLOPT_POST => true,
  223. CURLOPT_HTTPHEADER => [
  224. "Authorization: Bearer {$this->apiKey}",
  225. "Content-Type: application/json",
  226. "Accept: text/event-stream",
  227. ],
  228. CURLOPT_POSTFIELDS => json_encode($payload),
  229. CURLOPT_RETURNTRANSFER => false,
  230. CURLOPT_TIMEOUT => 0,
  231. CURLOPT_HEADER => false,
  232. CURLOPT_FOLLOWLOCATION => true,
  233. CURLOPT_WRITEFUNCTION => function (\CurlHandle $curl, string $data) use (&$fullContent, &$errorMessage): int {
  234. $lines = explode("\n", $data);
  235. foreach ($lines as $line) {
  236. $line = trim($line);
  237. if (!str_starts_with($line, 'data: ')) {
  238. continue;
  239. }
  240. $json = substr($line, 6);
  241. if ($json === '[DONE]') {
  242. continue;
  243. }
  244. $obj = json_decode($json, true);
  245. if (!is_array($obj)) {
  246. continue;
  247. }
  248. // 检查是否有错误
  249. if (isset($obj['error'])) {
  250. $errorMessage = $obj['error']['message'] ?? 'Stream error';
  251. return 0; // 停止接收
  252. }
  253. $delta = $obj['choices'][0]['delta']['content'] ?? '';
  254. if ($delta !== '') {
  255. $fullContent .= $delta;
  256. }
  257. }
  258. return strlen($data);
  259. },
  260. ]);
  261. curl_exec($ch);
  262. $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  263. if ($curlError = curl_error($ch)) {
  264. curl_close($ch);
  265. throw new NetworkException("CURL 错误: {$curlError}");
  266. }
  267. curl_close($ch);
  268. // 检查流式响应中的错误
  269. if ($errorMessage) {
  270. if ($httpCode === 429) {
  271. throw new RateLimitException($errorMessage, $httpCode);
  272. } elseif ($httpCode >= 500) {
  273. throw new ServerErrorException($errorMessage, $httpCode);
  274. } elseif ($httpCode >= 400) {
  275. throw new ClientErrorException($errorMessage, $httpCode);
  276. } else {
  277. throw new \RuntimeException($errorMessage, $httpCode);
  278. }
  279. }
  280. // 检查 HTTP 状态码
  281. if ($httpCode === 429) {
  282. throw new RateLimitException('请求被限流', $httpCode);
  283. } elseif ($httpCode >= 500) {
  284. throw new ServerErrorException('服务器错误', $httpCode);
  285. } elseif ($httpCode >= 400) {
  286. throw new ClientErrorException('客户端请求错误', $httpCode);
  287. } elseif ($httpCode < 200 || $httpCode >= 300) {
  288. throw new \RuntimeException("HTTP 错误: {$httpCode}");
  289. }
  290. return $fullContent;
  291. }
  292. }
  293. /**
  294. * 速率限制异常(429)
  295. */
  296. class RateLimitException extends \RuntimeException
  297. {
  298. protected int $retryAfter;
  299. public function __construct(string $message, int $code = 429, int $retryAfter = 20)
  300. {
  301. parent::__construct($message, $code);
  302. $this->retryAfter = $retryAfter;
  303. }
  304. public function getRetryAfter(): int
  305. {
  306. return $this->retryAfter;
  307. }
  308. public function getStatusCode(): int
  309. {
  310. return $this->code;
  311. }
  312. }
  313. /**
  314. * 服务器错误异常(5xx)
  315. */
  316. class ServerErrorException extends \RuntimeException
  317. {
  318. public function __construct(string $message, int $code = 500)
  319. {
  320. parent::__construct($message, $code);
  321. }
  322. public function getStatusCode(): int
  323. {
  324. return $this->code;
  325. }
  326. }
  327. /**
  328. * 客户端错误异常(4xx,除429外)
  329. */
  330. class ClientErrorException extends \RuntimeException
  331. {
  332. public function __construct(string $message, int $code = 400)
  333. {
  334. parent::__construct($message, $code);
  335. }
  336. public function getStatusCode(): int
  337. {
  338. return $this->code;
  339. }
  340. }
  341. /**
  342. * 网络错误异常
  343. */
  344. class NetworkException extends \RuntimeException
  345. {
  346. public function __construct(string $message, int $code = 0, ?\Throwable $previous = null)
  347. {
  348. parent::__construct($message, $code, $previous);
  349. }
  350. }