AIGatewayService.php 27 KB

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