AIGatewayService.php 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687
  1. <?php
  2. namespace app\service;
  3. use think\Db;
  4. use think\Queue;
  5. class AIGatewayService{
  6. /**
  7. * 接口访问配置
  8. *
  9. * 每个模块包含:
  10. * - api_key:API 调用密钥(Token)
  11. * - api_url:对应功能的服务端地址
  12. */
  13. protected $config = [
  14. //图生文-gemini-2.5-flash-preview
  15. 'imgtotxt' => [
  16. 'api_key' => 'sk-LVcDfTx5SYK6pWiGpfcAN2KA0LunymnMiYSVfzUKQXrjlkZv',
  17. 'api_url' => 'https://chatapi.onechats.top/v1/chat/completions'
  18. ],
  19. //文生文-gtp-4
  20. 'txttotxtgtp' => [
  21. 'api_key' => 'sk-fxlawqVtbbQbNW0wInR3E4wsLo5JHozDC2XOHzMa711su6ss',
  22. 'api_url' => 'https://chatapi.onechats.top/v1/chat/completions'
  23. ],
  24. //文生文-gemini-2.0-flash
  25. 'txttotxtgemini' => [
  26. 'api_key' => 'sk-cqfCZFiiSIdpDjIHLMBbH6uWfeg7iVsASvlubjrNEmfUXbpX',
  27. 'api_url' => 'https://chatapi.onechats.top/v1/chat/completions'
  28. ],
  29. //文生图-dall-e-3
  30. 'txttoimg' => [
  31. // 'api_key' => 'sk-MB6SR8qNaTjO80U7HJl4ztivX3zQKPgKVka9oyfVSXIkHSYZ',
  32. 'api_key' => 'sk-iURfrAgzAjhZ4PpPLwzmWIAhM7zKfrkwDvyxk4RVBQ4ouJNK',
  33. 'api_url' => 'https://chatapi.onechats.ai/v1/images/generations'
  34. ]
  35. ];
  36. /**
  37. * 图生文
  38. * @param string $imageUrl 图像 URL,支持公网可访问地址
  39. * @param string $prompt 对图像的提问内容或提示文本
  40. */
  41. public function callGptApi($imageUrl, $prompt)
  42. {
  43. //方式一
  44. $data = [
  45. "model" => "gemini-2.5-flash-lite-preview-06-17",
  46. "messages" => [[
  47. "role" => "user",
  48. "content" => [
  49. ["type" => "text", "text" => $prompt],
  50. ["type" => "image_url", "image_url" => [
  51. "url" => $imageUrl,
  52. "detail" => "auto"
  53. ]]
  54. ]
  55. ]],
  56. "max_tokens" => 1000
  57. ];
  58. //方式二
  59. // $data = [
  60. // "model" => "gpt-4-vision-preview",
  61. // "messages" => [[
  62. // "role" => "user",
  63. // "content" => [
  64. // ["type" => "text", "text" => $prompt],
  65. // ["type" => "image_url", "image_url" => [
  66. // "url" => $imageUrl,
  67. // "detail" => "auto"
  68. // ]]
  69. // ]
  70. // ]],
  71. // "max_tokens" => 1000
  72. // ];
  73. return $this->callApi($this->config['imgtotxt']['api_url'], $this->config['imgtotxt']['api_key'], $data);
  74. }
  75. /**
  76. * 文生文
  77. * @param string $prompt 用户输入的文本提示内容
  78. */
  79. public function txtGptApi($prompt,$txttotxt_selectedOption)
  80. {
  81. if (empty($prompt)) {
  82. throw new \Exception("Prompt 不允许为空");
  83. }
  84. //判断使用模型
  85. if ($txttotxt_selectedOption === 'gemini-2.0-flash') {
  86. $data = [
  87. 'model' => 'gemini-2.0-flash',
  88. 'messages' => [
  89. ['role' => 'user', 'content' => $prompt]
  90. ],
  91. 'temperature' => 0.7,
  92. 'max_tokens' => 1024
  93. ];
  94. return $this->callApi(
  95. $this->config['txttotxtgemini']['api_url'],
  96. $this->config['txttotxtgemini']['api_key'],
  97. $data
  98. );
  99. }else if ($txttotxt_selectedOption === 'gpt-4') {
  100. $data = [
  101. 'model' => 'gpt-4',
  102. 'messages' => [
  103. ['role' => 'user', 'content' => $prompt]
  104. ],
  105. 'temperature' => 0.7,
  106. 'max_tokens' => 1024
  107. ];
  108. return $this->callApi(
  109. $this->config['txttotxtgtp']['api_url'],
  110. $this->config['txttotxtgtp']['api_key'],
  111. $data
  112. );
  113. }
  114. }
  115. /**
  116. * 文生图
  117. *
  118. * @param string $prompt 提示文本,用于指导图像生成(最长建议 1000 字符)
  119. * @param string $selectedOption 模型名称,例如 'dall-e-3' 或其他兼容模型
  120. *
  121. * 默认参数说明(适用于所有模型):
  122. * - n: 1(生成 1 张图)
  123. * - size: '1024x1024'(标准正方形图像)
  124. * - quality: 'hd'(高清质量)
  125. * - style: 'vivid'(鲜明风格)
  126. *
  127. * response_format 参数差异:
  128. * - 若模型为 'dall-e-3':返回 base64 图像,字段为 `b64_json`
  129. * - 其他模型默认返回图像 URL,字段为 `url`
  130. *
  131. * ⚠️ 注意:使用此方法后,需在 Job/TextToImageJob.php 中按 response_format 判断提取方式:
  132. * 提取 url 图像
  133. * $base64Image = $dalle1024['data'][0]['url'] ?? null;
  134. * 提取 base64 图像
  135. * $base64Image = $dalle1024['data'][0]['b64_json'] ?? null;
  136. *
  137. * @return array 返回接口响应,成功时包含 'data' 字段,失败时包含 'error' 信息
  138. */
  139. public function callDalleApi($prompt, $selectedOption)
  140. {
  141. if ($selectedOption === 'dall-e-3') {
  142. $data = [
  143. 'prompt' => $prompt,
  144. 'model' => $selectedOption,
  145. 'n' => 1,
  146. // 'size' => '512x512',
  147. 'size' => '1024x1024',
  148. 'quality' => 'hd',
  149. 'style' => 'vivid',
  150. 'response_format' => 'url',
  151. ];
  152. } else if ($selectedOption === 'black-forest-labs/FLUX.1-kontext-pro') {
  153. $data = [
  154. 'prompt' => $prompt,
  155. 'model' => $selectedOption,
  156. 'n' => 1,
  157. // 'size' => '512x512',
  158. 'size' => '1024x1024',
  159. 'quality' => 'hd',
  160. 'style' => 'vivid',
  161. 'response_format' => 'url',
  162. ];
  163. }else{
  164. $data = [
  165. 'prompt' => $prompt,
  166. 'model' => $selectedOption,
  167. 'n' => 1,
  168. // 'size' => '512x512',
  169. 'size' => '1024x1024',
  170. 'quality' => 'hd',
  171. 'style' => 'vivid',
  172. 'response_format' => 'url',
  173. ];
  174. }
  175. return $this->callApi($this->config['txttoimg']['api_url'],$this->config['txttoimg']['api_key'],$data);
  176. }
  177. /**
  178. * 图生图
  179. * @param string $prompt 用户输入的文本提示内容
  180. * @param string $new_image_url 原图路径
  181. * @param array $options 可选参数,可覆盖默认配置
  182. * @return array
  183. */
  184. public function txt2imgWithControlNet($prompt, $controlImgUrl, $options = []) {
  185. $apiUrl = "http://20.0.17.188:45001/sdapi/v1/txt2img";
  186. $headers = ['Content-Type: application/json'];
  187. $imgPath = ROOT_PATH . 'public/' . ltrim($controlImgUrl, '/');
  188. if (!file_exists($imgPath)) {
  189. return ['code' => 1, 'msg' => '图片不存在:' . $controlImgUrl];
  190. }
  191. $imgData = file_get_contents($imgPath);
  192. $base64Img = 'data:image/png;base64,' . base64_encode($imgData);
  193. $params = [
  194. 'prompt' => $prompt,
  195. 'negative_prompt' => '(deformed, distorted, disfigured:1.3), poorly drawn, bad anatomy',
  196. 'steps' => 20,
  197. 'sampler_name' => 'DPM++ 2M SDE',
  198. 'cfg_scale' => 7,
  199. 'seed' => -1,
  200. 'width' => 1024,
  201. 'height' => 1303,
  202. 'override_settings' => [
  203. 'sd_model_checkpoint' => 'realisticVisionV51_v51VAE-inpainting',
  204. 'sd_vae' => 'vae-ft-mse-840000-ema-pruned',
  205. 'CLIP_stop_at_last_layers' => 2
  206. ],
  207. 'clip_skip' => 2,
  208. 'alwayson_scripts' => [
  209. 'controlnet' => [
  210. 'args' => [[
  211. 'enabled' => true,
  212. 'input_image' => $base64Img,
  213. 'module' => 'inpaint_only+lama',
  214. 'model' => 'control_v11p_sd15_inpaint_fp16 [be8bc0ed]',
  215. 'weight' => 1,
  216. 'resize_mode' => 'Resize and Fill',
  217. 'pixel_perfect' => false,
  218. 'control_mode' => 'ControlNet is more important',
  219. 'starting_control_step' => 0,
  220. 'ending_control_step' => 1
  221. ]]
  222. ]
  223. ]
  224. ];
  225. if (!empty($options)) {
  226. $params = array_merge($params, $options);
  227. }
  228. $ch = curl_init();
  229. curl_setopt($ch, CURLOPT_URL, $apiUrl);
  230. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  231. curl_setopt($ch, CURLOPT_POST, true);
  232. curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
  233. curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($params, JSON_UNESCAPED_UNICODE));
  234. curl_setopt($ch, CURLOPT_TIMEOUT, 180);
  235. $response = curl_exec($ch);
  236. $error = curl_error($ch);
  237. curl_close($ch);
  238. if ($error) {
  239. return ['code' => 1, 'msg' => '请求失败:' . $error];
  240. }
  241. $data = json_decode($response, true);
  242. if (!isset($data['images'][0])) {
  243. return ['code' => 1, 'msg' => '接口未返回图像数据'];
  244. }
  245. return [
  246. 'code' => 0,
  247. 'msg' => '成功',
  248. 'data' => [
  249. 'base64' => $data['images'][0],
  250. 'info' => $data['info'] ?? ''
  251. ]
  252. ];
  253. }
  254. // 第一阶段:图生图
  255. public function upscaleWithImg2Img($prompt, $imgPath)
  256. {
  257. if (!file_exists($imgPath)) {
  258. return ['code' => 1, 'msg' => '原图不存在:' . $imgPath];
  259. }
  260. // 获取原始图像尺寸
  261. [$origWidth, $origHeight] = getimagesize($imgPath);
  262. if (!$origWidth || !$origHeight) {
  263. return ['code' => 1, 'msg' => '无法识别图片尺寸'];
  264. }
  265. // 按2倍尺寸计算目标大小
  266. $targetWidth = $origWidth * 2;
  267. $targetHeight = $origHeight * 2;
  268. // 编码图像为 base64
  269. $imgData = file_get_contents($imgPath);
  270. $base64Img = 'data:image/png;base64,' . base64_encode($imgData);
  271. // 构造参数
  272. $params = [
  273. 'init_images' => [$base64Img],
  274. 'prompt' => $prompt,
  275. 'steps' => 20,
  276. 'sampler_name' => 'DPM++ 2M SDE Heun',
  277. 'cfg_scale' => 7,
  278. 'seed' => 1669863506,
  279. 'width' => $targetWidth,
  280. 'height' => $targetHeight,
  281. 'denoising_strength' => 0.2,
  282. 'clip_skip' => 2,
  283. 'override_settings' => [
  284. 'sd_model_checkpoint' => 'realisticVisionV51_v51VAE-inpainting.safetensors [f0d4872d24]',
  285. 'sd_vae' => 'vae-ft-mse-840000-ema-pruned.safetensors',
  286. 'CLIP_stop_at_last_layers' => 2
  287. ],
  288. 'override_settings_restore_afterwards' => true
  289. ];
  290. $apiUrl = "http://20.0.17.188:45001/sdapi/v1/img2img";
  291. $headers = ['Content-Type: application/json'];
  292. // 发起请求
  293. $ch = curl_init();
  294. curl_setopt_array($ch, [
  295. CURLOPT_URL => $apiUrl,
  296. CURLOPT_RETURNTRANSFER => true,
  297. CURLOPT_POST => true,
  298. CURLOPT_HTTPHEADER => $headers,
  299. CURLOPT_POSTFIELDS => json_encode($params),
  300. CURLOPT_TIMEOUT => 180
  301. ]);
  302. $response = curl_exec($ch);
  303. $error = curl_error($ch);
  304. curl_close($ch);
  305. if ($error) return ['code' => 1, 'msg' => '图生图请求失败:' . $error];
  306. $data = json_decode($response, true);
  307. if (!isset($data['images'][0])) return ['code' => 1, 'msg' => '图生图接口未返回图像'];
  308. return ['code' => 0, 'data' => ['base64' => $data['images'][0]]];
  309. }
  310. // 第二阶段:高清超分
  311. public function imgtogqGptApi($imageRelPath, $options = [])
  312. {
  313. $imgPath = ROOT_PATH . 'public/' . $imageRelPath;
  314. if (!file_exists($imgPath)) {
  315. return ['code' => 1, 'msg' => '原图不存在:' . $imageRelPath];
  316. }
  317. $defaultParams = [
  318. 'resize_mode' => 0,
  319. 'show_extras_results' => true,
  320. 'gfpgan_visibility' => 0,
  321. 'codeformer_visibility' => 0,
  322. 'codeformer_weight' => 0,
  323. 'upscaling_resize' => 1.62,
  324. 'upscaling_crop' => true,
  325. 'upscaler_1' => 'R-ESRGAN 4x+ Anime6B',
  326. 'upscaler_2' => 'None',
  327. 'extras_upscaler_2_visibility' => 0,
  328. 'upscale_first' => false
  329. ];
  330. $params = array_merge($defaultParams, $options);
  331. try {
  332. $imgData = file_get_contents($imgPath);
  333. if ($imgData === false) {
  334. throw new Exception('无法读取图片文件');
  335. }
  336. $params['image'] = base64_encode($imgData);
  337. } catch (Exception $e) {
  338. return ['code' => 1, 'msg' => '图片读取失败:' . $e->getMessage()];
  339. }
  340. $apiUrl = "http://20.0.17.188:45001/sdapi/v1/extra-single-image";
  341. $headers = ['Content-Type: application/json'];
  342. $ch = curl_init();
  343. curl_setopt_array($ch, [
  344. CURLOPT_URL => $apiUrl,
  345. CURLOPT_RETURNTRANSFER => true,
  346. CURLOPT_POST => true,
  347. CURLOPT_HTTPHEADER => $headers,
  348. CURLOPT_POSTFIELDS => json_encode($params),
  349. CURLOPT_TIMEOUT => 120
  350. ]);
  351. $response = curl_exec($ch);
  352. $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  353. $curlErr = curl_error($ch);
  354. curl_close($ch);
  355. if ($curlErr) {
  356. return ['code' => 1, 'msg' => '请求失败:' . $curlErr];
  357. }
  358. if ($httpCode !== 200) {
  359. return ['code' => 1, 'msg' => 'API请求失败,HTTP状态码:' . $httpCode];
  360. }
  361. $data = json_decode($response, true);
  362. if (json_last_error() !== JSON_ERROR_NONE) {
  363. return ['code' => 1, 'msg' => 'API返回数据解析失败:' . json_last_error_msg()];
  364. }
  365. if (empty($data['image'])) {
  366. return ['code' => 1, 'msg' => '接口未返回有效的图像数据'];
  367. }
  368. return [
  369. 'code' => 0,
  370. 'msg' => '高清图生成成功',
  371. 'data' => [
  372. 'base64_image' => $data['image'],
  373. 'original_size' => strlen($imgData),
  374. 'processed_size' => strlen(base64_decode($data['image']))
  375. ]
  376. ];
  377. }
  378. // public function imgtogqGptApi($imageRelPath, $options = [])
  379. // {
  380. // // 构造图片路径
  381. // $imgPath = ROOT_PATH . 'public/' . $imageRelPath;
  382. //
  383. // if (!file_exists($imgPath)) {
  384. // return ['code' => 1, 'msg' => '原图不存在:' . $imageRelPath];
  385. // }
  386. //
  387. // // 默认放大配置
  388. // $defaultParams = [
  389. // 'resize_mode' => 0,
  390. // 'show_extras_results' => true,
  391. // 'gfpgan_visibility' => 0,
  392. // 'codeformer_visibility' => 0,
  393. // 'codeformer_weight' => 0,
  394. // 'upscaling_resize' => 2.45,
  395. // 'upscaling_crop' => true,
  396. // 'upscaler_1' => 'R-ESRGAN 4x+ Anime6B',
  397. // 'upscaler_2' => 'None',
  398. // 'extras_upscaler_2_visibility' => 0,
  399. // 'upscale_first' => false
  400. // ];
  401. //
  402. // // 合并配置参数
  403. // $params = array_merge($defaultParams, $options);
  404. //
  405. // // 编码原始图片
  406. // try {
  407. // $imgData = file_get_contents($imgPath);
  408. // if ($imgData === false) {
  409. // throw new Exception('无法读取图片文件');
  410. // }
  411. // $params['image'] = base64_encode($imgData);
  412. // } catch (Exception $e) {
  413. // return ['code' => 1, 'msg' => '图片读取失败:' . $e->getMessage()];
  414. // }
  415. //
  416. // $apiUrl = "http://20.0.17.188:45001/sdapi/v1/extra-single-image";
  417. // $headers = ['Content-Type: application/json'];
  418. //
  419. // // 调用接口
  420. // $ch = curl_init();
  421. // curl_setopt_array($ch, [
  422. // CURLOPT_URL => $apiUrl,
  423. // CURLOPT_RETURNTRANSFER => true,
  424. // CURLOPT_POST => true,
  425. // CURLOPT_HTTPHEADER => $headers,
  426. // CURLOPT_POSTFIELDS => json_encode($params),
  427. // CURLOPT_TIMEOUT => 120
  428. // ]);
  429. //
  430. // $response = curl_exec($ch);
  431. // $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  432. // $curlErr = curl_error($ch);
  433. // curl_close($ch);
  434. //
  435. // // 网络请求失败
  436. // if ($curlErr) {
  437. // return ['code' => 1, 'msg' => '请求失败:' . $curlErr];
  438. // }
  439. //
  440. // // 状态码错误
  441. // if ($httpCode !== 200) {
  442. // return ['code' => 1, 'msg' => 'API请求失败,HTTP状态码:' . $httpCode];
  443. // }
  444. //
  445. // // 解析响应
  446. // $data = json_decode($response, true);
  447. // if (json_last_error() !== JSON_ERROR_NONE) {
  448. // return ['code' => 1, 'msg' => 'API返回数据解析失败:' . json_last_error_msg()];
  449. // }
  450. //
  451. // if (empty($data['image'])) {
  452. // return ['code' => 1, 'msg' => '接口未返回有效的图像数据'];
  453. // }
  454. //
  455. // // 保存新图片
  456. // try {
  457. // $baseName = pathinfo($imageRelPath, PATHINFO_FILENAME);
  458. // $ext = pathinfo($imageRelPath, PATHINFO_EXTENSION);
  459. // $outputDir = 'uploads/extra_image/';
  460. // $outputPath = ROOT_PATH . 'public/' . $outputDir;
  461. //
  462. // if (!is_dir($outputPath)) {
  463. // mkdir($outputPath, 0755, true);
  464. // }
  465. //
  466. // $saveFileName = $baseName . '-hd.' . $ext;
  467. // $saveFullPath = $outputPath . $saveFileName;
  468. // $resultImg = base64_decode($data['image']);
  469. //
  470. // if ($resultImg === false || file_put_contents($saveFullPath, $resultImg) === false) {
  471. // throw new Exception('保存图片失败');
  472. // }
  473. //
  474. // return [
  475. // 'code' => 0,
  476. // 'msg' => '高清图生成成功',
  477. // 'data' => [
  478. // 'url' => '/' . $outputDir . $saveFileName,
  479. // 'original_size' => filesize($imgPath),
  480. // 'processed_size' => filesize($saveFullPath),
  481. // 'resolution' => getimagesize($saveFullPath)
  482. // ]
  483. // ];
  484. // } catch (Exception $e) {
  485. // return ['code' => 1, 'msg' => '保存失败:' . $e->getMessage()];
  486. // }
  487. // }
  488. /**
  489. * 通用 API 调用方法(支持重试机制)
  490. *
  491. * @param string $url 接口地址
  492. * @param string $apiKey 授权密钥(Bearer Token)
  493. * @param array $data 请求数据(JSON 格式)
  494. *
  495. * 功能说明:
  496. * - 使用 cURL 发送 POST 请求到指定 API 接口
  497. * - 设置请求头和超时时间等参数
  498. * - 支持最多重试 2 次,当接口调用失败时自动重试
  499. * - 返回成功时解析 JSON 响应为数组
  500. *
  501. * 异常处理:
  502. * - 若全部重试失败,将抛出异常并包含最后一次错误信息
  503. *
  504. * @return array 接口响应数据(成功时返回解析后的数组)
  505. * @throws \Exception 接口请求失败时抛出异常
  506. */
  507. public function callApi($url, $apiKey, $data)
  508. {
  509. $maxRetries = 2;
  510. $attempt = 0;
  511. $lastError = '';
  512. $httpCode = 0;
  513. $apiErrorDetail = '';
  514. while ($attempt <= $maxRetries) {
  515. try {
  516. $ch = curl_init();
  517. curl_setopt_array($ch, [
  518. CURLOPT_URL => $url,
  519. CURLOPT_RETURNTRANSFER => true,
  520. CURLOPT_POST => true,
  521. CURLOPT_POSTFIELDS => json_encode($data),
  522. CURLOPT_HTTPHEADER => [
  523. 'Content-Type: application/json',
  524. 'Authorization: Bearer ' . $apiKey
  525. ],
  526. CURLOPT_TIMEOUT => 120,
  527. CURLOPT_SSL_VERIFYPEER => true,
  528. CURLOPT_SSL_VERIFYHOST => 2,
  529. CURLOPT_CONNECTTIMEOUT => 30,
  530. CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  531. CURLOPT_FAILONERROR => true
  532. ]);
  533. $response = curl_exec($ch);
  534. $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  535. $curlError = curl_error($ch);
  536. if ($response === false) {
  537. throw new \Exception("请求发送失败: " . $curlError);
  538. }
  539. $result = json_decode($response, true);
  540. // 检查API返回的错误
  541. if (isset($result['error'])) {
  542. $apiErrorDetail = $result['error']['message'] ?? '';
  543. $errorType = $result['error']['type'] ?? '';
  544. // 常见错误类型映射
  545. $errorMessages = [
  546. 'invalid_request_error' => '请求参数错误',
  547. 'authentication_error' => '认证失败',
  548. 'rate_limit_error' => '请求频率过高',
  549. 'insufficient_quota' => '额度不足',
  550. 'billing_not_active' => '账户未开通付费',
  551. 'content_policy_violation' => '内容违反政策'
  552. ];
  553. $friendlyMessage = $errorMessages[$errorType] ?? 'API服务错误';
  554. throw new \Exception("{$friendlyMessage}: {$apiErrorDetail}");
  555. }
  556. if ($httpCode !== 200) {
  557. // HTTP状态码映射
  558. $statusMessages = [
  559. 400 => '请求参数不合法',
  560. 401 => 'API密钥无效或权限不足',
  561. 403 => '访问被拒绝',
  562. 404 => 'API端点不存在',
  563. 429 => '请求过于频繁,请稍后再试',
  564. 500 => '服务器内部错误',
  565. 503 => '服务暂时不可用'
  566. ];
  567. $statusMessage = $statusMessages[$httpCode] ?? "HTTP错误({$httpCode})";
  568. throw new \Exception($statusMessage);
  569. }
  570. curl_close($ch);
  571. return $result;
  572. } catch (\Exception $e) {
  573. $lastError = $e->getMessage();
  574. $attempt++;
  575. if ($attempt <= $maxRetries) {
  576. sleep(pow(2, $attempt));
  577. } else {
  578. // 最终失败时的详细错误信息
  579. $errorDetails = [
  580. '错误原因' => $this->getErrorCause($httpCode, $apiErrorDetail),
  581. '解决方案' => $this->getErrorSolution($httpCode),
  582. '请求参数' => json_encode($data, JSON_UNESCAPED_UNICODE),
  583. 'HTTP状态码' => $httpCode,
  584. '重试次数' => $attempt
  585. ];
  586. throw new \Exception("API请求失败\n" .
  587. "失败说明: " . $errorDetails['错误原因'] . "\n" .
  588. "建议解决方案: " . $errorDetails['解决方案'] . "\n" .
  589. "技术详情: HTTP {$httpCode} - " . $lastError);
  590. }
  591. }
  592. }
  593. }
  594. /**
  595. * 根据错误类型获取友好的错误原因
  596. */
  597. private function getErrorCause($httpCode, $apiError)
  598. {
  599. $causes = [
  600. 401 => 'API密钥无效、过期或没有访问权限',
  601. 400 => $apiError ?: '请求参数不符合API要求',
  602. 429 => '已达到API调用频率限制',
  603. 403 => '您的账户可能没有开通相关服务权限',
  604. 500 => 'OpenAI服务器处理请求时出错'
  605. ];
  606. return $causes[$httpCode] ?? '未知错误,请检查网络连接和API配置';
  607. }
  608. /**
  609. * 根据错误类型获取解决方案建议
  610. */
  611. private function getErrorSolution($httpCode)
  612. {
  613. $solutions = [
  614. 401 => '1. 检查API密钥是否正确 2. 确认密钥是否有访问权限 3. 尝试创建新密钥',
  615. 400 => '1. 检查请求参数 2. 验证提示词内容 3. 参考API文档修正参数',
  616. 429 => '1. 等待1分钟后重试 2. 升级账户提高限额 3. 优化调用频率',
  617. 403 => '1. 检查账户状态 2. 确认是否已开通付费 3. 联系OpenAI支持',
  618. 500 => '1. 等待几分钟后重试 2. 检查OpenAI服务状态页'
  619. ];
  620. return $solutions[$httpCode] ?? '1. 检查网络连接 2. 查看服务日志 3. 联系技术支持';
  621. }
  622. }