AIGatewayService.php 27 KB

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