🎨 前置:了解基础 LLM 调用与 Prompt 工程(Prompt 工程深度指南)。
1. 生成式多模态的三大方向
文本
│
┌──────┼──────┐
│ │ │
▼ ▼ ▼
图像 视频 音频
│ │ │
▼ ▼ ▼
图生图 图生视频 语音克隆
2. 文生图(Text-to-Image)
2.1 主流模型对比
| 模型 | 质量 | 速度 | 成本 | 控制粒度 | 开源 |
|---|---|---|---|---|---|
| DALL-E 3 | ⭐⭐⭐⭐⭐ | 快 | $0.04/张 | 中 | ❌ |
| Midjourney v6 | ⭐⭐⭐⭐⭐ | 快 | $10/月 | 低 | ❌ |
| Stable Diffusion XL | ⭐⭐⭐⭐ | 中 | 免费(本地) | 高 | ✅ |
| Flux.1 | ⭐⭐⭐⭐⭐ | 中 | 免费(本地) | 高 | ✅ |
| Ideogram | ⭐⭐⭐⭐⭐ | 快 | 免费层 | 低 | ❌ |
| Imagen 3 (Google) | ⭐⭐⭐⭐⭐ | 快 | $0.03/张 | 中 | ❌ |
2.2 DALL-E 3 API 调用
from openai import OpenAI
client = OpenAI()
response = client.images.generate(
model="dall-e-3",
prompt="一只橙色猫咪在温暖的午后阳光下打盹,背景是日式庭院,柔和的水彩画风",
size="1024x1024", # 1024x1024, 1024x1792, 1792x1024
quality="standard", # standard | hd
n=1,
)
image_url = response.data[0].url
print(image_url)
2.3 图像生成 Prompt 工程
# 优质 Prompt 结构
"""
[主体], [动作/状态], [环境/背景], [艺术风格], [光照/氛围], [视角/构图], [质量修饰词]
示例:
"一只银灰色的波斯猫[主体]在窗台上优雅地伸展[动作],
窗外是雨后的城市天际线[背景],
赛璐珞动画风格[风格],
柔和的侧光[光照],
中景平视[视角],
8K 超清细节[质量]"
"""
# 负面提示(Negative Prompt)— SD/Flux 专用
negative_prompt = """
blur, low quality, distorted face, extra fingers, mutated hands,
poorly drawn, bad anatomy, watermark, signature, text, cropped
"""
2.4 Stable Diffusion 本地部署
# 方法 1:使用 Ollama
ollama pull llava # Ollama 也支持部分视觉生成
# 方法 2:ComfyUI(推荐)
git clone https://github.com/comfyanonymous/ComfyUI.git
cd ComfyUI
pip install -r requirements.txt
python main.py
# 方法 3:Stable Diffusion WebUI AUTOMATIC1111
git clone https://github.com/AUTOMATIC1111/stable-diffusion-webui.git
cd stable-diffusion-webui
./webui.sh
# 使用 diffusers 库程序化调用
from diffusers import StableDiffusionXLPipeline
import torch
pipe = StableDiffusionXLPipeline.from_pretrained(
"stabilityai/stable-diffusion-xl-base-1.0",
torch_dtype=torch.float16,
variant="fp16",
).to("cuda")
image = pipe(
prompt="一只穿着太空服的柯基犬在火星表面奔跑,皮克斯动画风格",
negative_prompt="模糊,低质量,变形",
num_inference_steps=30,
guidance_scale=7.5,
).images[0]
image.save("corgi_mars.png")
3. 文生视频(Text-to-Video)
3.1 主流模型对比
| 模型 | 时长 | 分辨率 | 质量 | 成本 | 可用性 |
|---|---|---|---|---|---|
| Sora (OpenAI) | 60s | 1080p | ⭐⭐⭐⭐⭐ | 未公开 | 受限预览 |
| Runway Gen-3 | 16s | 720p/1080p | ⭐⭐⭐⭐⭐ | $0.35/秒 | 公开 API |
| Pika 2.0 | 3s | 720p | ⭐⭐⭐⭐ | 免费层 | 公开 |
| 可灵 (Kling) | 10s | 1080p | ⭐⭐⭐⭐⭐ | 积分制 | 国内可用 |
| Luma Dream Machine | 5s | 1080p | ⭐⭐⭐⭐ | 免费层 | 公开 |
| Stable Video Diffusion | 4s | 576x1024 | ⭐⭐⭐ | 免费 | 开源 |
3.2 Runway Gen-3 API 调用
import requests
API_KEY = "YOUR_RUNWAY_KEY"
response = requests.post(
"https://api.runwayml.com/v1/generations",
headers={"Authorization": f"Bearer {API_KEY}"},
json={
"task_type": "text_to_video",
"model": "gen3",
"prompt": "Aerial drone shot of a serene Japanese garden in autumn, with koi pond and red maple leaves gently falling",
"duration": 10, # seconds
"ratio": "16:9",
},
)
task_id = response.json()["id"]
# 轮询结果
import time
while True:
status = requests.get(
f"https://api.runwayml.com/v1/generations/{task_id}",
headers={"Authorization": f"Bearer {API_KEY}"},
).json()
if status["status"] == "succeeded":
print(f"视频 URL: {status['url']}")
break
elif status["status"] == "failed":
print("生成失败")
break
time.sleep(5)
3.3 视频生成 Prompt 技巧
视频 Prompt 需要描述时序动态:
# 差的 Prompt
"一只狗在公园玩"
# 好的 Prompt
"一只金毛犬在阳光明媚的公园草地上奔跑,
镜头从左向右缓慢平移,
背景中可以看到儿童游乐设施和其他遛狗的人,
画面从远景逐渐推近到狗狗的特写,
4K 电影级画质,温暖的午后光线"
4. 图生图(Image-to-Image)
4.1 ControlNet:精确控制生成
from diffusers import StableDiffusionControlNetPipeline, ControlNetModel
from PIL import Image
import torch
import cv2
import numpy as np
# 加载 ControlNet (Canny 边缘检测)
controlnet = ControlNetModel.from_pretrained(
"lllyasviel/sd-controlnet-canny",
torch_dtype=torch.float16,
).to("cuda")
pipe = StableDiffusionControlNetPipeline.from_pretrained(
"runwayml/stable-diffusion-v1-5",
controlnet=controlnet,
torch_dtype=torch.float16,
).to("cuda")
# 提取 Canny 边缘
image = Image.open("pose_reference.jpg")
image_np = np.array(image)
low_threshold = 100
high_threshold = 200
canny = cv2.Canny(image_np, low_threshold, high_threshold)
canny_image = Image.fromarray(canny)
# 基于边缘 + Prompt 生成
generated = pipe(
prompt="一个赛博朋克风格的少女,霓虹灯光",
image=canny_image,
num_inference_steps=20,
).images[0]
4.2 IP-Adapter:风格迁移
from diffusers import StableDiffusionPipeline
import torch
# IP-Adapter 允许用参考图控制生成风格/人物
pipe = StableDiffusionPipeline.from_pretrained(
"runwayml/stable-diffusion-v1-5",
torch_dtype=torch.float16,
).to("cuda")
pipe.load_ip_adapter(
"h94/IP-Adapter",
subfolder="models",
weight_name="ip-adapter_sd15.bin",
)
reference_image = Image.open("reference_style.jpg")
generated = pipe(
prompt="一只猫在森林中",
ip_adapter_image=reference_image,
num_inference_steps=25,
).images[0]
5. 批量生成流水线
import asyncio
from dataclasses import dataclass
from typing import List
@dataclass
class GenerationTask:
prompt: str
style_reference: str = None
output_path: str = None
class BatchGenerator:
def __init__(self, model="dall-e-3"):
self.model = model
self.client = OpenAI()
async def generate_single(self, task: GenerationTask):
response = self.client.images.generate(
model=self.model,
prompt=task.prompt,
size="1024x1024",
n=1,
)
# 下载并保存
import aiohttp
async with aiohttp.ClientSession() as session:
async with session.get(response.data[0].url) as resp:
image_data = await resp.read()
output = task.output_path or f"output/{hash(task.prompt)}.png"
with open(output, "wb") as f:
f.write(image_data)
return {"task": task.prompt, "output": output}
async def generate_batch(self, tasks: List[GenerationTask], concurrency=3):
semaphore = asyncio.Semaphore(concurrency)
async def bounded_generate(task):
async with semaphore:
return await self.generate_single(task)
results = await asyncio.gather(*[bounded_generate(t) for t in tasks])
return results
# 使用
tasks = [
GenerationTask("一只柴犬在樱花树下", output_path="shiba_sakura.png"),
GenerationTask("未来城市的夜景,赛博朋克风格", output_path="cyberpunk.png"),
GenerationTask("手绘风格的热带海滩", output_path="beach_sketch.png"),
]
generator = BatchGenerator()
results = asyncio.run(generator.generate_batch(tasks))
6. 版权与伦理边界
⚠️ 红线规则
├── 不生成真实人物的肖像(深度伪造)
├── 不生成暴力、色情、仇恨内容
├── 商业使用需确认模型授权条款
├── 生成的内容标注 "AI Generated"
├── 保留生成日志(Prompt、参数、时间戳)
└── 建立内容审核流水线(自动化 + 人工抽检)
| 模型 | 商用授权 | 内容限制 |
|---|---|---|
| DALL-E 3 | ✅ 全商用 | OpenAI 使用政策 |
| Midjourney | ✅ 付费计划 | 社区准则 |
| SDXL | ✅ 开放 | 自行负责审核 |
| Flux.1 | ✅ Apache 2.0 | 自行负责审核 |
7. 成本与选型
| 需求 | 推荐方案 | 成本/100张 |
|---|---|---|
| 快速原型 | DALL-E 3 | $4 |
| 高质量艺术 | Midjourney | $10/月 |
| 批量生产 | SDXL 本地 | ~$5 电费 |
| 精确控制 | Flux + ControlNet | ~$8 电费 |
| 视频短片 | Runway Gen-3 | $35/10s |
| 视频开源 | SVD + AnimateDiff | ~$15 电费 |
📂 相关阅读:
继续阅读
探索更多技术文章
浏览归档,发现更多关于系统设计、工具链和工程实践的内容。
「llm」更多文章
模型上下文协议(MCP)完整指南:从 Anthropic 标准到 AI 应用互操作性革命
系统拆解 Model Context Protocol(MCP)的设计哲学、协议分层和核心概念:Resources、Prompts、Tools、Sampling。 涵盖 MCP 与 Function Calling、插件系统、API 网关的区别与互补关系。 附架构全景图、协议消息格式详解,以及 MCP 在 Claude Desktop、Cline、Continue 等客户端中的实际运行机制。
多模态语音合成与识别:从 Whisper + TTS 到实时语音交互的 LLM 实践
系统拆解 LLM 语音技术栈:语音识别(ASR / Whisper)、语音合成(TTS / ElevenLabs / Coqui TTS)、语音活动检测(VAD)。 覆盖实时语音交互架构(流式识别 + 流式合成 + 打断机制)、多语言语音克隆、以及语音 Agent 的安全与隐私考量。 附完整的 Whisper API 集成、本地 TTS 部署、WebRTC 实时语音管道代码。
多模态视频分析:从关键帧抽取到时序理解的 LLM 视频理解实战
系统拆解 LLM 视频理解的技术路径:关键帧提取、时序编码(Temporal Modeling)、视觉-时序联合推理。 覆盖 Gemini 1.5 Pro(原生视频)、GPT-4o(帧序列)、Claude(关键帧截图)、Video-LLaMA 四种实现方式。 附视频摘要生成、动作识别、异常检测、教育内容分析四个场景的完整代码与成本优化策略。