2
0

OpenAIService.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  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. if (isset($this->thinking)) {
  156. $data['enable_thinking'] = $this->thinking;
  157. }
  158. if ($this->maxTokens > 0) {
  159. $data['max_tokens'] = $this->maxTokens;
  160. }
  161. $response = Http::withToken($this->apiKey)
  162. ->timeout($this->timeout)
  163. ->post($this->apiUrl, $data);
  164. $status = $response->status();
  165. $body = $response->json();
  166. // 处理 429 速率限制
  167. if ($status === 429) {
  168. $retryAfter = (int)($response->header('Retry-After') ?? 20);
  169. throw new RateLimitException(
  170. $body['error']['message'] ?? '请求被限流',
  171. $status,
  172. $retryAfter
  173. );
  174. }
  175. // 处理 5xx 服务器错误
  176. if ($status >= 500 && $status < 600) {
  177. throw new ServerErrorException(
  178. $body['error']['message'] ?? '服务器错误',
  179. $status
  180. );
  181. }
  182. // 处理 4xx 客户端错误
  183. if ($status >= 400 && $status < 500) {
  184. throw new ClientErrorException(
  185. $body['error']['message'] ?? '客户端请求错误',
  186. $status
  187. );
  188. }
  189. // 处理成功响应
  190. if ($response->successful()) {
  191. return $body;
  192. }
  193. // 其他未知错误
  194. throw new \RuntimeException(
  195. $body['error']['message'] ?? '请求失败',
  196. $status
  197. );
  198. }
  199. /**
  200. * 流式请求(使用原生 CURL SSE)
  201. */
  202. protected function sendStreaming(string $question): string
  203. {
  204. $payload = [
  205. 'model' => $this->model,
  206. 'messages' => [
  207. ['role' => 'system', 'content' => $this->systemPrompt],
  208. ['role' => 'user', 'content' => $question],
  209. ],
  210. 'temperature' => $this->temperature,
  211. 'stream' => true,
  212. ];
  213. if ($this->maxTokens > 0) {
  214. $payload['max_tokens'] = $this->maxTokens;
  215. }
  216. $ch = curl_init($this->apiUrl);
  217. $fullContent = '';
  218. $httpCode = 0;
  219. $errorMessage = '';
  220. curl_setopt_array($ch, [
  221. CURLOPT_POST => true,
  222. CURLOPT_HTTPHEADER => [
  223. "Authorization: Bearer {$this->apiKey}",
  224. "Content-Type: application/json",
  225. "Accept: text/event-stream",
  226. ],
  227. CURLOPT_POSTFIELDS => json_encode($payload),
  228. CURLOPT_RETURNTRANSFER => false,
  229. CURLOPT_TIMEOUT => 0,
  230. CURLOPT_HEADER => false,
  231. CURLOPT_FOLLOWLOCATION => true,
  232. CURLOPT_WRITEFUNCTION => function (\CurlHandle $curl, string $data) use (&$fullContent, &$errorMessage): int {
  233. $lines = explode("\n", $data);
  234. foreach ($lines as $line) {
  235. $line = trim($line);
  236. if (!str_starts_with($line, 'data: ')) {
  237. continue;
  238. }
  239. $json = substr($line, 6);
  240. if ($json === '[DONE]') {
  241. continue;
  242. }
  243. $obj = json_decode($json, true);
  244. if (!is_array($obj)) {
  245. continue;
  246. }
  247. // 检查是否有错误
  248. if (isset($obj['error'])) {
  249. $errorMessage = $obj['error']['message'] ?? 'Stream error';
  250. return 0; // 停止接收
  251. }
  252. $delta = $obj['choices'][0]['delta']['content'] ?? '';
  253. if ($delta !== '') {
  254. $fullContent .= $delta;
  255. }
  256. }
  257. return strlen($data);
  258. },
  259. ]);
  260. curl_exec($ch);
  261. $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  262. if ($curlError = curl_error($ch)) {
  263. curl_close($ch);
  264. throw new NetworkException("CURL 错误: {$curlError}");
  265. }
  266. curl_close($ch);
  267. // 检查流式响应中的错误
  268. if ($errorMessage) {
  269. if ($httpCode === 429) {
  270. throw new RateLimitException($errorMessage, $httpCode);
  271. } elseif ($httpCode >= 500) {
  272. throw new ServerErrorException($errorMessage, $httpCode);
  273. } elseif ($httpCode >= 400) {
  274. throw new ClientErrorException($errorMessage, $httpCode);
  275. } else {
  276. throw new \RuntimeException($errorMessage, $httpCode);
  277. }
  278. }
  279. // 检查 HTTP 状态码
  280. if ($httpCode === 429) {
  281. throw new RateLimitException('请求被限流', $httpCode);
  282. } elseif ($httpCode >= 500) {
  283. throw new ServerErrorException('服务器错误', $httpCode);
  284. } elseif ($httpCode >= 400) {
  285. throw new ClientErrorException('客户端请求错误', $httpCode);
  286. } elseif ($httpCode < 200 || $httpCode >= 300) {
  287. throw new \RuntimeException("HTTP 错误: {$httpCode}");
  288. }
  289. return $fullContent;
  290. }
  291. }
  292. /**
  293. * 速率限制异常(429)
  294. */
  295. class RateLimitException extends \RuntimeException
  296. {
  297. protected int $retryAfter;
  298. public function __construct(string $message, int $code = 429, int $retryAfter = 20)
  299. {
  300. parent::__construct($message, $code);
  301. $this->retryAfter = $retryAfter;
  302. }
  303. public function getRetryAfter(): int
  304. {
  305. return $this->retryAfter;
  306. }
  307. public function getStatusCode(): int
  308. {
  309. return $this->code;
  310. }
  311. }
  312. /**
  313. * 服务器错误异常(5xx)
  314. */
  315. class ServerErrorException extends \RuntimeException
  316. {
  317. public function __construct(string $message, int $code = 500)
  318. {
  319. parent::__construct($message, $code);
  320. }
  321. public function getStatusCode(): int
  322. {
  323. return $this->code;
  324. }
  325. }
  326. /**
  327. * 客户端错误异常(4xx,除429外)
  328. */
  329. class ClientErrorException extends \RuntimeException
  330. {
  331. public function __construct(string $message, int $code = 400)
  332. {
  333. parent::__construct($message, $code);
  334. }
  335. public function getStatusCode(): int
  336. {
  337. return $this->code;
  338. }
  339. }
  340. /**
  341. * 网络错误异常
  342. */
  343. class NetworkException extends \RuntimeException
  344. {
  345. public function __construct(string $message, int $code = 0, ?\Throwable $previous = null)
  346. {
  347. parent::__construct($message, $code, $previous);
  348. }
  349. }