造相-Z-Image-Turbo提示词自动化使用JavaScript开发动态提示词生成器你是不是也遇到过这样的烦恼想用AI画一张特定风格的人像比如“一个戴着贝雷帽、有着金色卷发、微笑的少女背景是巴黎街头”结果在提示词框里敲了半天出来的图却总是不对味——要么发型不对要么表情僵硬背景也糊成一团。对于Web开发者来说这种重复、繁琐的提示词调试过程简直是在浪费生命。我们擅长的是用代码解决问题而不是像个打字员一样一遍遍手动组合关键词。今天我们就来聊聊如何用你熟悉的JavaScript打造一个属于你自己的“动态提示词生成器”把造相-Z-Image-Turbo这类AI绘画模型的潜力真正变成你指尖可控的创意工具。简单来说这个工具的核心就是让用户通过简单的下拉菜单、复选框等界面元素选择“风格”、“发型”、“表情”、“背景”等标签然后你的JavaScript代码能像调酒师一样根据一套精心设计的配方将这些标签动态组合成一段高质量、结构化的Prompt并直接调用API生成图片。这不仅能极大提升创作效率更能让生成效果变得稳定、可控。下面我们就一步步来构建这个创意引擎。1. 为什么需要动态提示词生成器在深入代码之前我们先搞清楚为什么要做这件事。手动写提示词有几个明显的痛点效率低下每次创作都需要重新构思和输入冗长的描述重复劳动多。效果不稳定关键词的顺序、权重、组合方式稍有变化结果就可能天差地别难以复现优秀效果。门槛较高新手需要学习大量的“黑话”如masterpiece, best quality和语法如(keyword:1.3)表示权重才能写出有效的Prompt。缺乏系统性难以管理和复用经过验证的、针对特定风格或元素的优质提示词片段。而一个动态生成器恰恰能解决这些问题。它将最佳实践固化到代码逻辑里把复杂的Prompt工程变成了直观的“点选”操作。对于开发者而言这不仅是效率工具更是一个可以不断迭代、扩展的创意系统。2. 核心设计构建你的“提示词配方库”开发这个工具第一步不是写代码而是设计“配方”。你需要将AI绘画的要素拆解成可编程的模块。我们可以把生成一张人像的Prompt想象成这样一个结构[画面质量词] [主体描述人物发型表情服饰动作] [环境与背景] [风格与艺术家] [技术参数]接下来我们用JavaScript对象来构建这个配方库。这里我们以Node.js环境为例但思路同样适用于浏览器端。// promptRecipe.js - 我们的提示词配方库 const promptRecipe { // 1. 画面质量基底通常固定或可选 qualityBase: { high: masterpiece, best quality, ultra-detailed, 8k, standard: high quality, detailed, simple: }, // 2. 人物主体特征库 subject: { gender: { girl: 1girl, boy: 1boy, woman: 1woman, man: 1man }, hairStyle: { longStraight: long straight hair, shortCurl: short curly hair, twinTail: twintails, ponytail: ponytail, silver: silver hair, blonde: blonde hair }, expression: { smile: smiling, happy: happy, serious: serious expression, wink: winking, blush: blushing }, clothing: { casual: casual wear, t-shirt, dress: elegant dress, hanfu: traditional chinese hanfu, armor: fantasy armor }, action: { standing: standing, sitting: sitting on a chair, running: running, lookingAtViewer: looking at viewer } }, // 3. 环境与背景库 environment: { background: { street: city street background, nature: forest, sunlight through leaves, studio: studio lighting, clean background, cyberpunk: cyberpunk city, neon lights, classroom: classroom }, time: { day: daytime, night: night, sunset: sunset, golden hour } }, // 4. 艺术风格与光照库 style: { artStyle: { anime: anime style, realistic: photorealistic, realistic, oilPainting: oil painting style, sketch: pencil sketch, cyberpunkArt: cyberpunk art }, lighting: { cinematic: cinematic lighting, soft: soft lighting, rimLight: rim light, volumetric: volumetric light } }, // 5. 负面提示词避免出现的内容 negativePrompt: { common: lowres, bad anatomy, bad hands, text, error, missing fingers, extra digit, fewer digits, cropped, worst quality, low quality, normal quality, jpeg artifacts, signature, watermark, username, blurry, deformed face } }; module.exports promptRecipe;这个promptRecipe对象就是我们的核心“素材库”。每个属性都像一个分类清晰的调料架里面放着各种“风味”的提示词片段。3. 动态组合引擎从选择到Prompt有了配方库下一步就是编写“调酒”逻辑。我们需要一个函数根据用户的选择比如一个配置对象从配方库中选取对应的“调料”并按照一定规则混合。// promptGenerator.js - 动态提示词生成引擎 const promptRecipe require(./promptRecipe.js); class DynamicPromptGenerator { constructor(baseQuality high) { this.baseQuality promptRecipe.qualityBase[baseQuality] || promptRecipe.qualityBase.high; } /** * 根据用户选择生成最终Prompt * param {Object} userChoices - 用户的选择配置 * returns {Object} - 包含正向提示词和负向提示词的对象 */ generate(userChoices) { // 初始化提示词数组 let positiveParts []; let negativeParts [promptRecipe.negativePrompt.common]; // 默认加入通用负面词 // 1. 添加质量基底 positiveParts.push(this.baseQuality); // 2. 组合人物主体 const subject promptRecipe.subject; if (userChoices.gender subject.gender[userChoices.gender]) { positiveParts.push(subject.gender[userChoices.gender]); } if (userChoices.hairStyle subject.hairStyle[userChoices.hairStyle]) { positiveParts.push(subject.hairStyle[userChoices.hairStyle]); } // ... 类似地处理 expression, clothing, action // 为了代码简洁这里用循环处理所有可选的主体特征 [expression, clothing, action].forEach(feature { if (userChoices[feature] subject[feature] subject[feature][userChoices[feature]]) { positiveParts.push(subject[feature][userChoices[feature]]); } }); // 3. 组合环境与背景 const env promptRecipe.environment; if (userChoices.background env.background[userChoices.background]) { positiveParts.push(env.background[userChoices.background]); } if (userChoices.time env.time[userChoices.time]) { positiveParts.push(env.time[userChoices.time]); } // 4. 组合艺术风格 const style promptRecipe.style; if (userChoices.artStyle style.artStyle[userChoices.artStyle]) { positiveParts.push(style.artStyle[userChoices.artStyle]); } if (userChoices.lighting style.lighting[userChoices.lighting]) { positiveParts.push(style.lighting[userChoices.lighting]); } // 5. 处理用户自定义的额外提示词或负面词 if (userChoices.extraPositive) { positiveParts.push(userChoices.extraPositive); } if (userChoices.extraNegative) { negativeParts.push(userChoices.extraNegative); } // 6. 将数组拼接成字符串并用逗号和空格连接确保可读性 const positivePrompt positiveParts.filter(p p).join(, ); const negativePrompt negativeParts.filter(n n).join(, ); return { positive: positivePrompt, negative: negativePrompt }; } } // 使用示例 const generator new DynamicPromptGenerator(high); const myChoices { gender: girl, hairStyle: silver, expression: smile, clothing: casual, background: street, time: sunset, artStyle: anime, lighting: cinematic, extraPositive: sparkle eyes // 用户自定义的额外细节 }; const finalPrompt generator.generate(myChoices); console.log(正向提示词:, finalPrompt.positive); console.log(负向提示词:, finalPrompt.negative);运行上面的示例你会得到一段类似这样的结构化Promptmasterpiece, best quality, ultra-detailed, 8k, 1girl, silver hair, smiling, casual wear, t-shirt, city street background, sunset, golden hour, anime style, cinematic lighting, sparkle eyes看一段复杂、专业的提示词就这样通过简单的对象配置自动生成了逻辑清晰易于维护和扩展。4. 连接造相-Z-Image-Turbo API生成Prompt只是第一步我们还需要让它能驱动AI模型。这里我们模拟调用一个图像生成API。在实际项目中你需要替换成造相模型提供的真实API端点、认证信息和参数。// apiCaller.js - 调用图像生成API示例 const axios require(axios); // 需要先安装: npm install axios class ImageGenerationClient { constructor(apiKey, baseURL https://api.example-z-image-turbo.com/v1) { this.apiKey apiKey; this.baseURL baseURL; this.client axios.create({ baseURL: this.baseURL, headers: { Authorization: Bearer ${this.apiKey}, Content-Type: application/json } }); } /** * 生成图片 * param {String} positivePrompt - 正向提示词 * param {String} negativePrompt - 负向提示词 * param {Object} options - 其他参数如尺寸、步数等 * returns {PromiseString} - 图片的URL或Base64数据 */ async generateImage(positivePrompt, negativePrompt, options {}) { const defaultOptions { model: z-image-turbo, // 指定模型 width: 1024, height: 1024, steps: 20, cfg_scale: 7, sampler_name: DPM 2M Karras, seed: -1, // -1表示随机 ...options // 用户自定义选项覆盖默认值 }; const payload { prompt: positivePrompt, negative_prompt: negativePrompt, ...defaultOptions }; try { console.log(正在生成图像提示词: ${positivePrompt.substring(0, 100)}...); const response await this.client.post(/generate, payload); // 假设API返回 { data: { image_url: ... } } 或 { data: base64string } if (response.data response.data.image_url) { console.log(图像生成成功URL:, response.data.image_url); return response.data.image_url; } else if (response.data) { console.log(图像生成成功(Base64数据)); return response.data; // 返回Base64数据 } else { throw new Error(API响应格式异常); } } catch (error) { console.error(调用图像生成API失败:, error.message); if (error.response) { console.error(API响应错误:, error.response.data); } throw error; } } } // 整合使用从生成到调用 async function createImageFromChoices(userChoices) { const promptGenerator new DynamicPromptGenerator(); const prompts promptGenerator.generate(userChoices); const client new ImageGenerationClient(YOUR_API_KEY_HERE); try { const imageResult await client.generateImage( prompts.positive, prompts.negative, { width: 768, height: 1024 } // 可以动态传递更多参数 ); return imageResult; } catch (error) { // 处理错误例如重试、降级方案等 console.error(创建图像流程失败:, error); return null; } } // 执行 (async () { const imageUrl await createImageFromChoices(myChoices); // myChoices 是之前定义的配置 if (imageUrl) { console.log(最终图片地址:, imageUrl); // 这里可以将URL显示在前端或保存到数据库等 } })();这段代码展示了从用户选择到最终调用API的完整闭环。ImageGenerationClient类封装了API调用的细节使得业务逻辑非常清晰。5. 构建一个简单的Web界面前端思路为了让非开发者也能用我们可以用HTML、CSS和JavaScript快速搭建一个前端界面。!DOCTYPE html html langzh-CN head meta charsetUTF-8 title造相提示词工坊/title style body { font-family: sans-serif; max-width: 800px; margin: 20px auto; padding: 20px; } .control-group { margin-bottom: 20px; } label { display: block; margin-bottom: 5px; font-weight: bold; } select, input[typetext] { width: 100%; padding: 8px; margin-bottom: 10px; } button { padding: 10px 20px; background: #007bff; color: white; border: none; cursor: pointer; } #preview { background: #f8f9fa; padding: 15px; margin-top: 20px; white-space: pre-wrap; word-wrap: break-word; } #imageResult { max-width: 100%; margin-top: 20px; } /style /head body h1造相提示词工坊/h1 p通过选择以下选项自动生成高质量的AI绘画提示词。/p div classcontrol-group label forhairStyle发型/label select idhairStyle option valuelongStraight长直发/option option valuesilver银发/option option valueblonde金发/option option valuetwinTail双马尾/option /select label forexpression表情/label select idexpression option valuesmile微笑/option option valuehappy开心/option option valueserious严肃/option option valuewink眨眼/option /select label forbackground背景/label select idbackground option valuestreet城市街道/option option valuenature自然森林/option option valuecyberpunk赛博朋克都市/option option valueclassroom教室/option /select label forartStyle艺术风格/label select idartStyle option valueanime动漫风格/option option valuerealistic写实风格/option option valueoilPainting油画风格/option /select label forextraPositive额外描述可选/label input typetext idextraPositive placeholder例如戴着眼镜手里拿着书 button onclickgenerateAndPreview()生成提示词并预览/button button onclickgenerateImage() idgenerateBtn生成图像/button /div div idpreview strong生成的提示词预览/strong div idpromptOutput等待生成.../div /div div idresultArea img idimageResult alt生成的图像将显示在这里 div idstatus/div /div script // 前端的简化版配方库也可以从后端加载 const frontendRecipe { hairStyle: { longStraight: long straight hair, silver: silver hair, blonde: blonde hair, twinTail: twintails }, expression: { smile: smiling, happy: happy, serious: serious expression, wink: winking }, background: { street: city street background, nature: forest, cyberpunk: cyberpunk city, classroom: classroom }, artStyle: { anime: anime style, realistic: photorealistic, oilPainting: oil painting style } }; function collectChoices() { return { hairStyle: document.getElementById(hairStyle).value, expression: document.getElementById(expression).value, background: document.getElementById(background).value, artStyle: document.getElementById(artStyle).value, extraPositive: document.getElementById(extraPositive).value.trim() }; } function generatePrompt(choices) { const base masterpiece, best quality, 1girl; let parts [base]; // 从配方库中获取对应的提示词片段 parts.push(frontendRecipe.hairStyle[choices.hairStyle]); parts.push(frontendRecipe.expression[choices.expression]); parts.push(frontendRecipe.background[choices.background]); parts.push(frontendRecipe.artStyle[choices.artStyle]); if (choices.extraPositive) { parts.push(choices.extraPositive); } // 过滤掉undefined如果某个选项没选并用逗号连接 return parts.filter(p p).join(, ); } function generateAndPreview() { const choices collectChoices(); const finalPrompt generatePrompt(choices); document.getElementById(promptOutput).textContent finalPrompt; } async function generateImage() { const btn document.getElementById(generateBtn); const statusDiv document.getElementById(status); const imgElement document.getElementById(imageResult); btn.disabled true; statusDiv.textContent 正在生成图像请稍候...; imgElement.style.display none; const choices collectChoices(); const finalPrompt generatePrompt(choices); try { // 这里需要替换为你的实际后端API端点 // 前端通常不直接暴露API Key应该通过自己的后端服务器转发请求 const response await fetch(/api/generate-image, { // 假设你有一个后端路由 method: POST, headers: { Content-Type: application/json }, body: JSON.stringify({ prompt: finalPrompt }) }); if (!response.ok) { throw new Error(HTTP error! status: ${response.status}); } const data await response.json(); if (data.imageUrl) { imgElement.src data.imageUrl; imgElement.style.display block; statusDiv.textContent 图像生成成功; } else { statusDiv.textContent 生成失败未收到图片URL。; } } catch (error) { console.error(生成失败:, error); statusDiv.textContent 生成失败: ${error.message}; } finally { btn.disabled false; } } // 初始化页面时生成一次预览 window.onload generateAndPreview; /script /body /html这个简单的界面展示了核心交互逻辑用户选择选项JavaScript实时组合提示词并预览点击按钮后通过后端为了保护API Key调用造相API最后将生成的图片展示出来。6. 总结与进阶思考通过上面的步骤我们已经完成了一个基础但完整的动态提示词生成器。它把原本需要手动钻研的Prompt工程变成了一个可视化、可配置的创意工具。对于开发者来说这个项目的价值远不止于此可扩展性你可以轻松地为配方库添加新的类别如“时代风格”复古、未来、“材质”丝绸、金属、“镜头语言”特写、全景。权重与高级语法可以在生成逻辑中加入权重控制比如将用户最关注的标签用(keyword:1.5)增强。模板与预设可以设计“古风少女”、“赛博朋克侦探”等一键生成的预设模板。历史与收藏将用户生成过的成功配方包括最终参数和图片保存下来形成可分享的“作品集”。A/B测试同时用微调后的两套提示词生成图片让用户选择更喜欢的效果从而优化你的配方库。用JavaScript开发这样的工具本质上是将你对AI模型的理解、对创意流程的洞察固化成一段段可执行的逻辑。它降低了使用门槛放大了创作效率让你和你的用户都能更专注于想法本身而不是与提示词语法搏斗。希望这个指南能为你打开一扇门去构建更强大、更智能的创意辅助系统。获取更多AI镜像想探索更多AI镜像和应用场景访问 CSDN星图镜像广场提供丰富的预置镜像覆盖大模型推理、图像生成、视频生成、模型微调等多个领域支持一键部署。