AIGatewayService.php 26 KB

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