如何使用 LLM Gateway 和 Vercel AI SDK 生成图像

发布: (2026年3月1日 GMT+8 06:14)
7 分钟阅读
原文: Dev.to

Source: Dev.to

LLM Gateway 与 Vercel AI SDK 生成图像的封面图

smakosh

图像生成已成为现代 AI 应用的核心功能。但与多个图像提供商集成——它们各自拥有不同的 API、定价和功能——可能会非常麻烦。

LLM Gateway 通过提供一个统一的、兼容 OpenAI 的图像生成 API,简化了这一过程,支持 Google Gemini、阿里巴巴 Qwen、字节跳动 Seedream 等多家提供商。在本指南中,我们将演示如何使用 OpenAI SDKVercel AI SDK 生成图像。

先决条件

  • 在 注册并创建项目。
  • 复制您的 API 密钥。

在环境中导出它:

export LLM_GATEWAY_API_KEY="llmgtwy_XXXXXXXXXXXXXXXX"

选项 1 – 图像 API (/v1/images/generations)

最简单的方法——直接替代 OpenAI 的图像生成端点。

使用 curl

curl -X POST "https://api.llmgateway.io/v1/images/generations" \
  -H "Authorization: Bearer $LLM_GATEWAY_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gemini-3-pro-image-preview",
    "prompt": "A cute cat wearing a tiny top hat",
    "n": 1,
    "size": "1024x1024"
  }'

使用 OpenAI SDK(Node.js)

import OpenAI from "openai";
import { writeFileSync } from "fs";

const client = new OpenAI({
  baseURL: "https://api.llmgateway.io/v1",
  apiKey: process.env.LLM_GATEWAY_API_KEY,
});

const response = await client.images.generate({
  model: "gemini-3-pro-image-preview",
  prompt: "A futuristic city skyline at sunset with flying cars",
  n: 1,
  size: "1024x1024",
});

response.data.forEach((image, i) => {
  if (image.b64_json) {
    const buf = Buffer.from(image.b64_json, "base64");
    writeFileSync(`image-${i}.png`, buf);
  }
});

就这么简单——将 baseURL 指向 LLM Gateway 并使用标准的 OpenAI SDK。无需额外库。

选项 2 – Vercel AI SDK (generateImage)

如果您已经在使用 Vercel AI SDK,LLM Gateway 提供了一个原生提供者包:@llmgateway/ai-sdk-provider

npm install @llmgateway/ai-sdk-provider ai

简单图像生成

import { createLLMGateway } from "@llmgateway/ai-sdk-provider";
import { generateImage } from "ai";
import { writeFileSync } from "fs";

const llmgateway = createLLMGateway({
  apiKey: process.env.LLM_GATEWAY_API_KEY,
});

const result = await generateImage({
  model: llmgateway.image("gemini-3-pro-image-preview"),
  prompt:
    "A cozy cabin in a snowy mountain landscape at night with aurora borealis",
  size: "1024x1024",
  n: 1,
});

result.images.forEach((image, i) => {
  const buf = Buffer.from(image.base64, "base64");
  writeFileSync(`image-${i}.png`, buf);
});

使用 streamText 进行对话式图像生成

真实的力量在于将图像生成与聊天结合。使用聊天‑completion 方法,你可以构建对话式图像生成流程——让模型创建图像,然后通过后续消息进行细化。

Next.js API Route

import {
  streamText,
  type UIMessage,
  convertToModelMessages,
} from "ai";
import { createLLMGateway } from "@llmgateway/ai-sdk-provider";

interface ChatRequestBody {
  messages: UIMessage[];
}

export async function POST(req: Request) {
  const body = await req.json();
  const { messages }: ChatRequestBody = body;

  const llmgateway = createLLMGateway({
    apiKey: process.env.LLM_GATEWAY_API_KEY,
    baseUrl: "https://api.llmgateway.io/v1",
  });

  try {
    const result = streamText({
      model: llmgateway.chat("gemini-3-pro-image-preview"),
      messages: convertToModelMessages(messages),
    });

    return result.toUIMessageStreamResponse();
  } catch {
    return new Response(
      JSON.stringify({ error: "LLM Gateway Chat request failed" }),
      { status: 500 }
    );
  }
}

前端 Hook (useChat)

import { useChat } from "@ai-sdk/react";

export const ImageChat = () => {
  const { messages, status, sendMessage } = useChat();

  return (
    
      {messages.map((m) => {
        if (m.role === "assistant") {
          const textContent = m.parts
            .filter((p) => p.type === "text")
            .map((p) => p.text)
            .join("");

          const imageParts = m.parts.filter(
            (p) => p.type === "file" && p.mediaType?.startsWith("image/")
          );

          return (
            
              {textContent && 
{textContent}
}
              {imageParts.map((part, idx) => (
                
              ))}
            
          );
        }

        return (
          
            {m.parts.map((p, i) => (
              
{p.type === "text" ? p.text : null}

            ))}
          
        );
      })}
    
  );
};

通过这些代码片段,你可以生成单张图像、批量图像,甚至使用 LLM Gateway 与 OpenAI SDK 或 Vercel AI SDK 一起构建完整的对话式图像生成 UI。祝编码愉快!

Source:

使用 LLM Gateway 生成图像

下面是使用 LLM Gateway 生成、编辑以及切换图像提供商的快速指南。

1️⃣ 生成图像

import { Image } from "ai-elements";

export const ImageDemo = () => {
  const { data, error, isLoading } = useChatCompletion({
    model: "gemini-3-pro-image-preview",
    messages: [
      {
        role: "user",
        content: [
          {
            type: "text",
            text: "Create a futuristic cityscape at sunset"
          }
        ]
      }
    ],
    // optional: control size/quality
    image_config: {
      aspect_ratio: "16:9",
      image_size: "4K"
    }
  });

  if (isLoading) return 
Loading…
;
  if (error) return 
{error.message}
;

  return (
    
      {data?.choices?.map((c, i) => (
        
          {c.message?.content?.map((p, i) =>
            p.type === "image" ? (
              
            ) : p.type === "text" ? (
              
{p.text}

            ) : null
          )}
        
      ))}
    
  );
};

提示: 你也可以使用 ai-elements 中的预构建 “ 组件,以获得更精致的渲染体验。

2️⃣ 图像编辑

LLM Gateway 支持通过 /v1/images/edits 对已有图像进行编辑。提供图像 URL(HTTPS 或 base64 数据 URL)以及编辑提示:

curl -X POST "https://api.llmgateway.io/v1/images/edits" \
  -H "Authorization: Bearer $LLM_GATEWAY_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "images": [
      {
        "image_url": "https://example.com/source-image.png"
      }
    ],
    "prompt": "Add a watercolor effect to this image",
    "model": "gemini-3-pro-image-preview",
    "quality": "high",
    "size": "1024x1024"
  }'

3️⃣ 切换提供商

更换图像提供商只需 单行 编辑——将 model 字符串替换即可:

// Google Gemini
model: "gemini-3-pro-image-preview"

// Alibaba Qwen (from $0.03/image)
model: "alibaba/qwen-image-plus"

// ByteDance Seedream (up to 4K output)
model: "bytedance/seedream-4-5"

// Z.AI CogView (great for text in images)
model: "zai/cogview-4"

提供商对比

提供商模型价格(每张图片)最适合
Googlegemini-3-pro-image-preview视情况而定通用用途,高质量
Alibabaalibaba/qwen-image-max$0.075最高质量
Alibabaalibaba/qwen-image-plus$0.03性价比最高
ByteDancebytedance/seedream-4-5$0.045支持最高 4K,支持多图融合
Z.AIzai/cogview-4$0.01最便宜,支持双语文字渲染

4️⃣ 自定义输出

使用 image_config 参数(用于聊天补全)或标准的 size/quality 参数(用于 Images API)来控制生成结果。

// Google: 长宽比 + 分辨率
{
  "image_config": {
    "aspect_ratio": "16:9",
    "image_size": "4K"
  }
}

// Alibaba: 像素尺寸 + seed(可复现)
{
  "image_config": {
    "image_size": "1024x1536",
    "seed": 42
  }
}

结束语

使用 LLM Gateway,图像生成变得 供应商无关。无论您使用 OpenAI SDK、Vercel AI SDK,还是原始 HTTP,您都可以获得:

  • 一个 API 适用于多家供应商
  • 轻松切换模型,无需更改代码
  • 对尺寸、质量和宽高比的细粒度控制

资源

开始使用 →

0 浏览
Back to Blog

相关文章

阅读更多 »

当工作成为心理健康风险时

markdown !Ravi Mishrahttps://media2.dev.to/dynamic/image/width=50,height=50,fit=cover,gravity=auto,format=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fu...