AIGatewayService.php 26 KB

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