AIGatewayService.php 28 KB

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