AIGatewayService.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  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 调用密钥(Bearer Token)
  11. * - api_url:对应功能的服务端地址
  12. */
  13. protected $config = [
  14. //图生文
  15. 'imgtotxt' => [
  16. 'api_key' => 'sk-scyWT2YPrPOIzralcb6WzCeFdAZvl91rh1JcuuaNMrhEJNDZ',
  17. 'api_url' => 'https://niubi.zeabur.app/v1/chat/completions'
  18. ],
  19. //文生文
  20. 'txttotxt' => [
  21. 'api_key' => 'sk-Bhos1lXTRpZiAAmN06624a219a874eCd91Dc068b902a3e73',
  22. 'api_url' => 'https://one.opengptgod.com/v1/chat/completions'
  23. ],
  24. // //文生图
  25. // 'txttoimg' => [
  26. // 'api_key' => 'sk-Bhos1lXTRpZiAAmN06624a219a874eCd91Dc068b902a3e73',
  27. // 'api_url' => 'https://one.opengptgod.com/v1/chat/completions'
  28. // ]
  29. // //文生图【权限不足】
  30. 'txttoimg' => [
  31. 'api_key' => 'sk-e0JuPjMntkbgi1BoMjrqyyzMKzAxILkQzyGMSy3xiMupuoWY',
  32. 'api_url' => 'https://niubi.zeabur.app/v1/images/generations'
  33. ]
  34. ];
  35. /**
  36. * 图生文
  37. * @param string $imageUrl 图像 URL,支持公网可访问地址
  38. * @param string $prompt 对图像的提问内容或提示文本
  39. */
  40. public function callGptApi($imageUrl, $prompt)
  41. {
  42. $data = [
  43. "model" => "gemini-2.5-pro-preview-05-06",
  44. "messages" => [[
  45. "role" => "user",
  46. "content" => [
  47. ["type" => "text", "text" => $prompt],
  48. ["type" => "image_url", "image_url" => [
  49. "url" => $imageUrl,
  50. "detail" => "auto"
  51. ]]
  52. ]
  53. ]],
  54. "max_tokens" => 1000
  55. ];
  56. return $this->callApi($this->config['imgtotxt']['api_url'], $this->config['imgtotxt']['api_key'], $data);
  57. }
  58. /**
  59. * 图生文-方法二
  60. * @param string $imageUrl 图像 URL,支持公网可访问地址
  61. * @param string $prompt 对图像的提问内容或提示文本
  62. */
  63. // public function callGptApi($imageUrl, $prompt)
  64. // {
  65. // $data = [
  66. // "model" => "gpt-4-vision-preview",
  67. // "messages" => [[
  68. // "role" => "user",
  69. // "content" => [
  70. // ["type" => "text", "text" => $prompt],
  71. // ["type" => "image_url", "image_url" => [
  72. // "url" => $imageUrl,
  73. // "detail" => "auto"
  74. // ]]
  75. // ]
  76. // ]],
  77. // "max_tokens" => 1000
  78. // ];
  79. // return $this->callApi($this->config['imgtotxt']['api_url'], $this->config['imgtotxt']['api_key'], $data);
  80. // }
  81. /**
  82. * 文生文
  83. * @param string $prompt 用户输入的文本提示内容
  84. */
  85. public function txtGptApi($prompt)
  86. {
  87. $data = [
  88. 'prompt' => $prompt,
  89. 'model' => 'gpt-4',
  90. 'session_id' => null,
  91. 'context_reset' => true
  92. ];
  93. return $this->callApi(
  94. $this->config['txttotxt']['api_url'],
  95. $this->config['txttotxt']['api_key'],
  96. $data
  97. );
  98. }
  99. /**
  100. * 文生文-超结损分析
  101. * @param string $prompt 用户输入的文本提示内容
  102. */
  103. // public function chaojiesunGptApi($prompt)
  104. // {
  105. // $data = [
  106. // 'prompt' => $prompt,
  107. // 'model' => 'gpt-4',
  108. // 'session_id' => null,
  109. // 'context_reset' => true
  110. // ];
  111. // return $this->callApi(
  112. // $this->config['chaojiesun']['api_url'],
  113. // $this->config['chaojiesun']['api_key'],
  114. // $data
  115. // );
  116. // }
  117. /**
  118. * 文生图
  119. * @param string $prompt 提示文本,用于指导图像生成
  120. * @param string $selectedOption 模型名称,例如 'dall-e-3' 或其他兼容模型
  121. */
  122. public function callDalleApi($prompt,$selectedOption)
  123. {
  124. if($selectedOption == 'dall-e-3'){
  125. $data = [
  126. 'prompt' => $prompt,
  127. 'model' => $selectedOption,
  128. 'n' => 1,
  129. 'size' => '1024x1024',
  130. 'quality' => 'standard',
  131. 'style' => 'vivid',
  132. 'response_format' => 'url',
  133. 'session_id' => null,
  134. 'context_reset' => true
  135. ];
  136. }else{
  137. $data = [
  138. 'prompt' => $prompt,
  139. 'model' => $selectedOption,
  140. 'n' => 1,
  141. 'size' => '1024x1024',
  142. 'quality' => 'hd',
  143. 'style' => 'vivid',
  144. 'response_format' => 'url',
  145. 'session_id' => null,
  146. 'context_reset' => true
  147. ];
  148. }
  149. return $this->callApi($this->config['txttoimg']['api_url'], $this->config['txttoimg']['api_key'], $data);
  150. }
  151. public function imgtoimgGptApi($prompt, $new_image_url)
  152. {
  153. $imgPath = ROOT_PATH . 'public/' . $new_image_url;
  154. if (!file_exists($imgPath)) {
  155. return ['code' => 1, 'msg' => '原图不存在:' . $new_image_url];
  156. }
  157. // 原图 base64 编码
  158. $imgData = file_get_contents($imgPath);
  159. $base64Img = base64_encode($imgData);
  160. $initImage = 'data:image/png;base64,' . $base64Img;
  161. // 构建 POST 请求参数
  162. $postData = json_encode([
  163. 'prompt' => $prompt,
  164. 'sampler_name' => 'DPM++ 2M SDE Heun',
  165. 'seed' => -1,
  166. 'steps' => 20,
  167. 'cfg_scale' => 7,
  168. 'denoising_strength' => 0.6,
  169. 'width' => 1024,
  170. 'height' => 2048,
  171. 'resize_mode' => 0,
  172. 'inpaint_full_res' => true,
  173. 'inpainting_fill' => 1,
  174. 'init_images' => [$initImage],
  175. 'override_settings' => [
  176. 'sd_model_checkpoint' => 'realisticVisionV51_v51VAE-inpainting.safetensors [f0d4872d24]',
  177. 'sd_vae' => 'anything-v4.5.vae.pt'
  178. ]
  179. ]);
  180. $apiUrl = "http://20.0.17.233:45001/sdapi/v1/img2img";
  181. $headers = ['Content-Type: application/json'];
  182. $ch = curl_init();
  183. curl_setopt($ch, CURLOPT_URL, $apiUrl);
  184. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  185. curl_setopt($ch, CURLOPT_POST, true);
  186. curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
  187. curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
  188. curl_setopt($ch, CURLOPT_TIMEOUT, 90);
  189. $response = curl_exec($ch);
  190. $error = curl_error($ch);
  191. curl_close($ch);
  192. if ($error) {
  193. return ['code' => 1, 'msg' => '请求失败:' . $error];
  194. }
  195. $data = json_decode($response, true);
  196. if (!isset($data['images'][0])) {
  197. return ['code' => 1, 'msg' => 'API未返回图像数据'];
  198. }
  199. return [
  200. 'code' => 0,
  201. 'msg' => '图像生成成功',
  202. 'data' => [
  203. 'url' => $data['images'][0]
  204. ]
  205. ];
  206. }
  207. /**
  208. * 通用 API 调用方法(支持重试机制)
  209. *
  210. * @param string $url 接口地址
  211. * @param string $apiKey 授权密钥(Bearer Token)
  212. * @param array $data 请求数据(JSON 格式)
  213. *
  214. * 功能说明:
  215. * - 使用 cURL 发送 POST 请求到指定 API 接口
  216. * - 设置请求头和超时时间等参数
  217. * - 支持最多重试 2 次,当接口调用失败时自动重试
  218. * - 返回成功时解析 JSON 响应为数组
  219. *
  220. * 异常处理:
  221. * - 若全部重试失败,将抛出异常并包含最后一次错误信息
  222. *
  223. * @return array 接口响应数据(成功时返回解析后的数组)
  224. * @throws \Exception 接口请求失败时抛出异常
  225. */
  226. public function callApi($url, $apiKey, $data)
  227. {
  228. $maxRetries = 2;
  229. $attempt = 0;
  230. $lastError = '';
  231. $httpCode = 0;
  232. $apiErrorDetail = '';
  233. while ($attempt <= $maxRetries) {
  234. try {
  235. $ch = curl_init();
  236. curl_setopt_array($ch, [
  237. CURLOPT_URL => $url,
  238. CURLOPT_RETURNTRANSFER => true,
  239. CURLOPT_POST => true,
  240. CURLOPT_POSTFIELDS => json_encode($data),
  241. CURLOPT_HTTPHEADER => [
  242. 'Content-Type: application/json',
  243. 'Authorization: Bearer ' . $apiKey
  244. ],
  245. CURLOPT_TIMEOUT => 120,
  246. CURLOPT_SSL_VERIFYPEER => true,
  247. CURLOPT_SSL_VERIFYHOST => 2,
  248. CURLOPT_CONNECTTIMEOUT => 30,
  249. CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  250. CURLOPT_FAILONERROR => true
  251. ]);
  252. $response = curl_exec($ch);
  253. $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  254. $curlError = curl_error($ch);
  255. if ($response === false) {
  256. throw new \Exception("请求发送失败: " . $curlError);
  257. }
  258. $result = json_decode($response, true);
  259. // 检查API返回的错误
  260. if (isset($result['error'])) {
  261. $apiErrorDetail = $result['error']['message'] ?? '';
  262. $errorType = $result['error']['type'] ?? '';
  263. // 常见错误类型映射
  264. $errorMessages = [
  265. 'invalid_request_error' => '请求参数错误',
  266. 'authentication_error' => '认证失败',
  267. 'rate_limit_error' => '请求频率过高',
  268. 'insufficient_quota' => '额度不足',
  269. 'billing_not_active' => '账户未开通付费',
  270. 'content_policy_violation' => '内容违反政策'
  271. ];
  272. $friendlyMessage = $errorMessages[$errorType] ?? 'API服务错误';
  273. throw new \Exception("{$friendlyMessage}: {$apiErrorDetail}");
  274. }
  275. if ($httpCode !== 200) {
  276. // HTTP状态码映射
  277. $statusMessages = [
  278. 400 => '请求参数不合法',
  279. 401 => 'API密钥无效或权限不足',
  280. 403 => '访问被拒绝',
  281. 404 => 'API端点不存在',
  282. 429 => '请求过于频繁,请稍后再试',
  283. 500 => '服务器内部错误',
  284. 503 => '服务暂时不可用'
  285. ];
  286. $statusMessage = $statusMessages[$httpCode] ?? "HTTP错误({$httpCode})";
  287. throw new \Exception($statusMessage);
  288. }
  289. curl_close($ch);
  290. return $result;
  291. } catch (\Exception $e) {
  292. $lastError = $e->getMessage();
  293. $attempt++;
  294. if ($attempt <= $maxRetries) {
  295. sleep(pow(2, $attempt));
  296. } else {
  297. // 最终失败时的详细错误信息
  298. $errorDetails = [
  299. '错误原因' => $this->getErrorCause($httpCode, $apiErrorDetail),
  300. '解决方案' => $this->getErrorSolution($httpCode),
  301. '请求参数' => json_encode($data, JSON_UNESCAPED_UNICODE),
  302. 'HTTP状态码' => $httpCode,
  303. '重试次数' => $attempt
  304. ];
  305. throw new \Exception("API请求失败\n" .
  306. "失败说明: " . $errorDetails['错误原因'] . "\n" .
  307. "建议解决方案: " . $errorDetails['解决方案'] . "\n" .
  308. "技术详情: HTTP {$httpCode} - " . $lastError);
  309. }
  310. }
  311. }
  312. }
  313. /**
  314. * 根据错误类型获取友好的错误原因
  315. */
  316. private function getErrorCause($httpCode, $apiError)
  317. {
  318. $causes = [
  319. 401 => 'API密钥无效、过期或没有访问权限',
  320. 400 => $apiError ?: '请求参数不符合API要求',
  321. 429 => '已达到API调用频率限制',
  322. 403 => '您的账户可能没有开通相关服务权限',
  323. 500 => 'OpenAI服务器处理请求时出错'
  324. ];
  325. return $causes[$httpCode] ?? '未知错误,请检查网络连接和API配置';
  326. }
  327. /**
  328. * 根据错误类型获取解决方案建议
  329. */
  330. private function getErrorSolution($httpCode)
  331. {
  332. $solutions = [
  333. 401 => '1. 检查API密钥是否正确 2. 确认密钥是否有访问权限 3. 尝试创建新密钥',
  334. 400 => '1. 检查请求参数 2. 验证提示词内容 3. 参考API文档修正参数',
  335. 429 => '1. 等待1分钟后重试 2. 升级账户提高限额 3. 优化调用频率',
  336. 403 => '1. 检查账户状态 2. 确认是否已开通付费 3. 联系OpenAI支持',
  337. 500 => '1. 等待几分钟后重试 2. 检查OpenAI服务状态页'
  338. ];
  339. return $solutions[$httpCode] ?? '1. 检查网络连接 2. 查看服务日志 3. 联系技术支持';
  340. }
  341. // public function callApi($url, $apiKey, $data)
  342. // {
  343. // $maxRetries = 2; // 最多重试次数
  344. // $attempt = 0; // 当前尝试次数
  345. // $lastError = ''; // 最后一次错误信息
  346. //
  347. // while ($attempt <= $maxRetries) {
  348. // $ch = curl_init();
  349. // curl_setopt_array($ch, [
  350. // CURLOPT_URL => $url,
  351. // CURLOPT_RETURNTRANSFER => true,
  352. // CURLOPT_POST => true,
  353. // CURLOPT_POSTFIELDS => json_encode($data),
  354. // CURLOPT_HTTPHEADER => [
  355. // 'Content-Type: application/json',
  356. // 'Authorization: Bearer ' . $apiKey
  357. // ],
  358. // CURLOPT_TIMEOUT => 120,
  359. // CURLOPT_SSL_VERIFYPEER => false,
  360. // CURLOPT_SSL_VERIFYHOST => 0,
  361. // CURLOPT_TCP_KEEPALIVE => 1,
  362. // CURLOPT_FORBID_REUSE => false
  363. // ]);
  364. //
  365. // $response = curl_exec($ch);
  366. // $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  367. // $curlError = curl_error($ch);
  368. // curl_close($ch);
  369. //
  370. // if ($response !== false && $httpCode === 200) {
  371. // $result = json_decode($response, true);
  372. // return $result;
  373. // }
  374. //
  375. // $lastError = $curlError ?: "HTTP错误:{$httpCode}";
  376. // $attempt++;
  377. // sleep(1);
  378. // }
  379. //
  380. // throw new \Exception("请求失败(重试{$maxRetries}次):{$lastError}");
  381. // }
  382. }