PHP 怎么接 AI 生图 API?甜甜圈API 的 Guzzle 写法(含 Laravel 队列)

做电商后台、CMS 的项目里 PHP 存量很大,但 AIGC 接口 的 PHP 示例特别少。其实不需要任何 SDK------甜甜圈APIdashengfenshen.cn)兼容 OpenAI 的 chat/completions 协议,Guzzle 直接调就行。

一、接口信息

Base URL https://dashengfenshen.cn
接口 POST /v1/chat/completions
鉴权 Authorization: Bearer {你的API密钥}

二、最小实现

复制代码
<?php
namespace App\Services;

use GuzzleHttp\Client;

class TtqImage
{
    private Client $http;

    public function __construct()
    {
        $this->http = new Client([
            'base_uri' => 'https://dashengfenshen.cn',
            // 生图慢,超时必须给足。Guzzle 默认 timeout=0(不超时),
            // 网络一抖请求会永久挂住,把 php-fpm 的进程占死
            'timeout'  => 120,
            'connect_timeout' => 10,
        ]);
    }

    public function generate(string $prompt, string $model = 'nano-banana-pro'): array
    {
        $res = $this->http->post('/v1/chat/completions', [
            'headers' => ['Authorization' => 'Bearer ' . env('TTQ_API_KEY')],
            'json' => [
                'model' => $model,
                'messages' => [['role' => 'user', 'content' => $prompt]],
            ],
        ]);
        return json_decode((string) $res->getBody(), true);
    }
}

密钥放 .env,别硬编码进代码、更别提交进仓库。

三、别在 HTTP 请求里同步等

生图接口动辄十几秒,同步等会把 php-fpm 的进程池占满------并发一上来整站都卡。丢进队列:

复制代码
// app/Jobs/GenerateImage.php
class GenerateImage implements ShouldQueue
{
    public $timeout = 180;      // 必须 > 接口超时,否则任务先被杀
    public $tries = 3;
    public $backoff = [10, 30]; // 指数退避,别固定间隔

    public function __construct(public int $taskId, public string $prompt) {}

    public function handle(TtqImage $api): void
    {
        $data = $api->generate($this->prompt);
        Task::where('id', $this->taskId)->update([
            'status' => 'done',
            'result' => json_encode($data),
        ]);
    }

    public function failed(\Throwable $e): void
    {
        Task::where('id', $this->taskId)->update(['status' => 'failed', 'error' => $e->getMessage()]);
    }
}

控制器只管接单:

复制代码
public function create(Request $r)
{
    $task = Task::create(['status' => 'pending', 'prompt' => $r->input('prompt')]);
    GenerateImage::dispatch($task->id, $r->input('prompt'));
    return response()->json(['taskId' => $task->id]);   // 立刻返回
}

前端拿 taskId 轮询状态即可。三个容易踩的:队列 timeout 要大于接口超时失败要写 failed() 回调 (不然任务永远停在 pending)、.env 改完记得 php artisan config:clear

四、模型怎么选

模型代码 说明 消耗
nano-banana2 Flash 级,跑量首选 8 积分/次
nano-banana-pro Pro 级,支持 1K/2K/4K 10 积分/次
gpt-image-2 细节质感好,适合终稿 按次计费
ttq-cutout 抠图出白底图 10 积分/次
Veo 3.1 视频生成 / Sora 2 生视频 120 / 130 积分/次

换模型只改 model 字符串,方法签名都不用动。

五、小结

PHP 接AI绘画API 的要点:Guzzle 的 timeout 一定要设、生图丢队列别同步等、队列超时要大于接口超时、密钥走 .env

甜甜圈APIdashengfenshen.cn)的 OpenAI 兼容协议让 PHP 完全不需要 SDK。模型全价格便宜 (积分制明码标价)、并发高出图快稳定。文档地址:https://dashengfenshen.cn

相关推荐
badhope3382 小时前
当所有AI都在抄同一份作业:前端模板的趋同、困局与破局
前端·ai·ai编程·前端开发·tailwind·ui设计
产品设计大观5 小时前
构建低消耗的产研AI工作流:Workbuddy生态 + 墨刀AI 落地实践
人工智能·ai·产品经理·墨刀·腾讯·产品设计·workbuddy
(轻舟已过万重山)7 小时前
第27章 框架实操:用 LangChain/LlamaIndex 搭建完整 RAG 系统
人工智能·ai·langchain
Smoothcloud润云8 小时前
GPU租赁数据安全怎么做?
人工智能·算法·ai·aigc·gpu算力·gpu
晴天168 小时前
AtomCode深度解析-Day09
人工智能·ai
weixin_431600449 小时前
做 Agent 会用到的 Node API(3):异步与流
前端·学习·ai·agent·ai编程
小七-七牛开发者9 小时前
Agent 小知识|长任务不重来:Agent 状态保存的工程设计
ai·大模型·agent·claude·token·工作流·skill·claudecode·ai coding
安逸sgr10 小时前
Zero-shot、Few-shot 和 One-shot Prompt 有什么区别?
人工智能·ai·大模型·agent·智能体
AI办公探索者11 小时前
多租户架构下数据隔离的三种实现方案对比
数据库·ai·oracle·架构