商品目录的 SEO 工作既重复又繁重:数百件商品都需要搜索标题、元描述和图片替代文本。相比长时间推理,更重要的是稳定和低成本。本教程使用 IaGenify 中价格最低的 Gemini 4 模型 Hydrogen,并通过 JSON Schema 保证每次返回相同结构。
读取商品
商品保存在 IaGenify Cloud SQL 数据库中。SDK 每次执行一条语句,并返回对应的数据行。
import { IaGenify } from "iagenify";
const api = new IaGenify({ apiKey: process.env.IAGENIFY_API_KEY });
const db = (await api.storage.list()).find((storage) => storage.label === "Shop");
const { rows } = await db.run({
action: "execute",
sql: "SELECT id, name, description, category FROM products WHERE seo_title IS NULL LIMIT ?",
params: [200],
});要求固定结构,而不是自由文本
通过 Schema 创建的会话会返回匹配该结构的 JSON。模型会读取 Schema 中的字段说明,因此长度和语气要求应写在那里。设置 `memory: false` 可让每件商品的处理互不影响。
const writer = await api.models.create({
model: "gemini-4-hydrogen",
memory: false,
settings: { temperature: 0.2, instructions: "You write e-commerce SEO in the product's own language." },
schema: {
type: "object",
properties: {
title: { type: "string", description: "Search title, 60 characters at most" },
description: { type: "string", description: "Meta description, 155 characters at most" },
alt: { type: "string", description: "Factual alt text for the main photo, 120 characters at most" },
},
required: ["title", "description", "alt"],
},
});写回结果
for (const product of rows) {
const { outputs } = await writer.generate({
inputs: [{ type: "text", content: JSON.stringify(product) }],
});
const seo = outputs[0].content;
await db.run({
action: "execute",
sql: "UPDATE products SET seo_title = ?, seo_description = ?, image_alt = ? WHERE id = ?",
params: [seo.title, seo.description, seo.alt, product.id],
});
}模型输出只作为绑定参数传递,绝不会拼入 SQL 语句。先处理少量商品并检查结果,再逐步提高数量上限。
费用
Hydrogen 每百万输入 token 收取 375 额度,每百万输出 token 收取 1,875 额度;1 个额度等于 1 美分。每次调用按整额度向上取整,因此一件简短商品约需 2 个额度,200 件约需 400 个额度。`api.catalogue()` 会返回当前价格,脚本可以在运行前估算批次费用。
参考资料
常见问题
为什么用 Schema,而不是在提示词中要求 JSON?
Schema 会约束最终回答,因此每件商品都会返回相同的三个字段,可直接保存。
Python 的用法相同吗?
相同。`api.models.create(model=..., schema=...)` 和 `db.run(action="execute", sql=..., params=[...])` 使用同样的参数结构。