Generative AI for Beginners 第 9 课:使用 DALL-E 与 Azure OpenAI 构建图像生成应用
【免费下载链接】generative-ai-for-beginners21 Lessons, Get Started Building with Generative AI项目地址: https://gitcode.com/GitHub_Trending/ge/generative-ai-for-beginners
本课聚焦于生成式 AI 的图像生成能力:从文本描述生成图像,并围绕 DALL-E / gpt-image-1 这类图像模型构建可运行的 Python 应用。文章以 translations/id/09-building-image-applications/README.md(对应英文原版 09-building-image-applications/README.md)为骨架,结合 09-building-image-applications/python/ 下的仓库源码展开。你将掌握:搭建 Azure OpenAI 图像生成环境、调用client.images.generate生成图片、使用 temperature 控制输出随机性、利用 meta prompt 划定内容边界,以及图片编辑与变体等进阶能力。
为什么构建图像生成应用
LLM 的价值不止于文本生成——从文字描述生成图像的能力,为 MedTech、建筑、旅游、游戏开发等众多领域带来新的可能性。图像生成应用是探索生成式 AI 能力的绝佳载体,典型用途包括:
- 图像编辑与合成:为多种场景生成图像,例如对现有图片进行局部修改或合成新内容;
- 跨行业应用:医疗科技、旅游、游戏开发等行业都可以借助文本生成图像。
教学场景:Edu4All
本课延续项目中的创业公司场景 Edu4All:学生们需要为作业生成图像,例如为自己写的童话绘制插图、为故事设计新角色,或把抽象的想法与概念可视化。
比如当学生正在学习世界著名纪念碑时,他们可以生成这样的图像:
使用的提示词很简单:
"Dog next to Eiffel Tower in early morning sunlight"(清晨阳光下,埃菲尔铁塔旁的一只狗)
这一场景将在后面的任务与解决方案中再次出现,届时我们会用 meta prompt 约束输出,生成"巴黎凯旋门"主题的图片。
DALL-E 与 Midjourney 是什么
DALL-E 与 Midjourney 是两款最流行的图像生成模型,都允许你通过 prompt 生成图像。
DALL-E
DALL-E 是一个由文本描述生成图像的生成式 AI 模型。它由两个模型组合而成:CLIP与diffused attention:
- CLIP:从图像与文本中生成 embeddings(数据的数值表示);
- Diffused attention:从 embeddings 生成图像。DALL-E 在图像-文本数据集上训练,因此可以把文本描述映射为图像,例如"戴帽子的猫"或"莫霍克发型的狗"。
从架构上看,DALL-E 基于 transformer 架构中的autoregressive transformer(自回归 Transformer):它逐像素生成图像——先生成一个像素,再基于已生成的像素预测下一个像素,依次穿过神经网络的多个层,直到图像完成。通过这一过程,DALL-E 可以控制生成图像中的属性、对象、特征等;而 DALL-E 2 与 DALL-E 3 对生成图像拥有更强的控制力。
Midjourney
Midjourney 的工作方式与 DALL-E 类似:从文本 prompt 生成图像,同样支持"戴帽子的猫"、"莫霍克发型的狗"这类描述。两者定位不同——DALL-E 通过 API 编程调用,适合嵌入应用;Midjourney 更常用于对话式/交互式创作,本课以可编程的 API 方案(Azure OpenAI)为主。
搭建第一个图像生成应用
构建图像生成应用需要以下 Python 库:
- python-dotenv:强烈建议用它把密钥存放在与代码分离的
.env文件中; - openai:用于与 OpenAI / Azure OpenAI API 交互;
- pillow:在 Python 中处理图像;
- requests:发起 HTTP 请求,用于下载生成的图片。
创建并部署 Azure OpenAI 模型
若尚未创建,请按 Microsoft Learn 指引创建 Azure OpenAI 资源与模型。当前一代 Azure OpenAI 图像模型为gpt-image-1(DALL-E 3 属旧版,新部署已不再提供);仓库中 aoai-app.py 与 TypeScript 版 main.ts 均默认采用该模型。
创建应用
1. 配置.env环境变量
AZURE_OPENAI_ENDPOINT=<your endpoint> AZURE_OPENAI_API_KEY=<your key> AZURE_OPENAI_DEPLOYMENT="gpt-image-1"这些信息可在 Azure OpenAI Foundry 门户的 "Deployments" 部分找到。
2. 编写requirements.txt
python-dotenv openai pillow requests与仓库根目录的 requirements.txt 及 09-building-image-applications/requirements.txt 保持一致。
3. 创建虚拟环境并安装依赖
python3 -m venv venv source venv/bin/activate pip install -r requirements.txtWindows 下创建与激活虚拟环境的命令:
python3 -m venv venv venv\Scripts\activate.bat4. 编写app.py
import openai import os import requests from PIL import Image import dotenv from openai import OpenAI, AzureOpenAI # import dotenv dotenv.load_dotenv() # configure Azure OpenAI service client client = AzureOpenAI( azure_endpoint = os.environ["AZURE_OPENAI_ENDPOINT"], api_key=os.environ['AZURE_OPENAI_API_KEY'], api_version = "2024-10-21" ) try: # Create an image by using the image generation API generation_response = client.images.generate( prompt='Bunny on horse, holding a lollipop, on a foggy meadow where it grows daffodils', size='1024x1024', n=1, model=os.environ['AZURE_OPENAI_DEPLOYMENT'] ) # Set the directory for the stored image image_dir = os.path.join(os.curdir, 'images') # If the directory doesn't exist, create it if not os.path.isdir(image_dir): os.mkdir(image_dir) # Initialize the image path (note the filetype should be png) image_path = os.path.join(image_dir, 'generated-image.png') # Retrieve the generated image image_url = generation_response.data[0].url # extract image URL from response generated_image = requests.get(image_url).content # download the image with open(image_path, "wb") as image_file: image_file.write(generated_image) # Display the image in the default image viewer image = Image.open(image_path) image.show() # catch exceptions except openai.BadRequestError as err: print(err)仓库中的 aoai-app.py 提供了几乎一致的实现,并额外展示了用result.model_dump_json()把响应序列化为 JSON 后再提取data[0]["url"]的写法,同时把模型名放入model = os.environ['AZURE_OPENAI_DEPLOYMENT']变量中复用,代码结构更便于维护。
逐段解读这段代码:
导入依赖:引入 OpenAI 库、dotenv 库、requests 库与 Pillow 库:
import openai import os import requests from PIL import Image import dotenv加载环境变量:
dotenv.load_dotenv()配置 Azure OpenAI 客户端:从环境变量读取 endpoint 与 key。注意
api_version需与所选模型匹配——仓库代码使用"2024-10-21"(旧版文档中的"2024-02-01"对应 DALL-E 3 时代),具体以 Microsoft Foundry 文档为准:client = AzureOpenAI( azure_endpoint = os.environ["AZURE_OPENAI_ENDPOINT"], api_key=os.environ['AZURE_OPENAI_API_KEY'], api_version = "2024-10-21" )生成图像:调用
client.images.generate,响应是包含生成图像 URL 的 JSON 对象:generation_response = client.images.generate( prompt='Bunny on horse, holding a lollipop, on a foggy meadow where it grows daffodils', size='1024x1024', n=1, model=os.environ['AZURE_OPENAI_DEPLOYMENT'] )下载并展示:用 URL 下载图片保存为 PNG 文件,再用系统默认查看器打开:
image = Image.open(image_path) image.show()
生成图片的更多细节
核心调用client.images.generate的参数含义:
- prompt:用于生成图像的文本提示。本例为 "Bunny on horse, holding a lollipop, on a foggy meadow where it grows daffodils"(雾霭草地上长满水仙花、小兔骑在马背上举着棒棒糖);
- size:生成图像的尺寸,本例为 1024x1024 像素;
- n:生成的图片数量;
- temperature:控制生成式 AI 模型输出的随机性,取值 0~1,0 表示输出确定,1 表示输出随机,默认 0.7(详细实验见下文"Temperature"一节)。
TypeScript 版本的仓库示例 main.ts 展示了同样的调用模式:new AzureOpenAI({ endpoint, apiKey, deployment, apiVersion })后调用client.images.generate({ model, prompt, n, size }),并遍历imageGenerations.data打印每张图片的 URL——与 Python 端接口一一对应。
图像生成的进阶能力
除了基础生成,还可以对图片做更多操作:
执行编辑(Edit)
提供一张已有图片、一个 mask(标识需要修改的区域)和一个 prompt,即可改变图片。例如给兔子图片"戴上帽子":提供原图、mask 与文字 prompt。注意:DALL-E 3 不支持此功能。
使用 GPT Image(gpt-image-1)的编辑示例:
response = client.images.edit( model="gpt-image-1", image=open("sunlit_lounge.png", "rb"), mask=open("mask.png", "rb"), prompt="A sunlit indoor lounge area with a pool containing a flamingo" ) image_url = response.data[0].url基础图片只包含带泳池的休息室,最终图片会多出一只火烈鸟:
创建变体(Variation)
思路是拿一张已有图片请求生成变体。需要提供图片与文字 prompt,示例代码:
response = client.images.create_variation( image=open("bunny-lollipop.png", "rb"), n=1, size="1024x1024" ) image_url = response.data[0].url注意:变体功能仅由 OpenAI 的 DALL-E 2 模型支持,gpt-image-1 不支持。
仓库中 oai-app.py 在生成完成后追加了client.images.create_variation(image=open(image_path, "rb"), n=1, size="1024x1024");oai-app-variation.py 则把变体写成独立流程:先打开之前生成的generated-image.png,调用变体接口,把结果保存为generated_variation.png并展示。需要留意的是,DALL-E 3 生成的图片目前还不能直接作为变体输入,使用前请确认所选模型的能力边界。
Temperature:控制输出的随机性
temperature是控制生成式 AI 模型输出随机性的参数,取值 0~1:0 表示输出确定(deterministic),1 表示输出随机(random),默认值为 0.7。
实验方法:把下面这条 prompt 连续运行两次——
Prompt: "Bunny on horse, holding a lollipop, on a foggy meadow where it grows daffodils"
再运行一次相同的 prompt,你会看到结果并不相同:
两张图片相似但不相同。为了让输出更确定,把 temperature 设为 0:
generation_response = client.images.generate( prompt='Bunny on horse, holding a lollipop, on a foggy meadow where it grows daffodils', # Enter your prompt text here size='1024x1024', n=2, temperature=0 )运行后得到两张图:
可以明显看到,temperature 设为 0 后两张图彼此更接近,说明随机性被显著压低。
用 Meta Prompt 为应用划定边界
演示应用已能为客户生成图片,但还需要为应用设定边界——例如不能生成不适合工作场合(not safe for work)或不适合儿童观看的图片。
Meta prompt(元提示词)就是用来控制生成式 AI 模型输出的文本 prompt。它的工作方式是:置于用户 prompt 之前,与应用集成,将"用户输入 prompt"与"meta prompt 输入"封装进同一个文本 prompt 中,从而约束模型的输出。
一个典型的 meta prompt 示例:
You are an assistant designer that creates images for children. The image needs to be safe for work and appropriate for children. The image needs to be in color. The image needs to be in landscape orientation. The image needs to be in a 16:9 aspect ratio. Do not consider any input from the following that is not safe for work or appropriate for children. (Input)把它应用到演示中——先声明一个disallow_list(禁用词列表),再与 meta prompt 模板拼接:
disallow_list = "swords, violence, blood, gore, nudity, sexual content, adult content, adult themes, adult language, adult humor, adult jokes, adult situations, adult" meta_prompt =f"""You are an assistant designer that creates images for children. The image needs to be safe for work and appropriate for children. The image needs to be in color. The image needs to be in landscape orientation. The image needs to be in a 16:9 aspect ratio. Do not consider any input from the following that is not safe for work or appropriate for children. {disallow_list} """ prompt = f"{meta_prompt} Create an image of a bunny on a horse, holding a lollipop" # TODO add request to generate image从上面的 prompt 可以看到,所有生成的图片都会把 meta prompt 作为约束纳入考虑:禁用词列表直接注入 meta prompt 中,即使用户输入里出现这些词,模型也会拒绝生成不安全/不适合儿童的内容。这正是"元提示词"把规则与用户输入封装在单一文本 prompt 中的实际体现。
任务:帮学生生成纪念碑图片
回到开头介绍的 Edu4All 场景:帮助学生为作业生成包含纪念碑的图片,具体生成哪座纪念碑由学生自行决定,鼓励发挥创意,把纪念碑放在不同的情境中。
参考解决方案如下(见 aoai-solution.py,响应序列化方式与带model参数的主应用一致):
import openai import os import requests from PIL import Image import dotenv from openai import AzureOpenAI # import dotenv dotenv.load_dotenv() # Get endpoint and key from environment variables client = AzureOpenAI( azure_endpoint = os.environ["AZURE_OPENAI_ENDPOINT"], api_key=os.environ['AZURE_OPENAI_API_KEY'], api_version = "2024-10-21" ) disallow_list = "swords, violence, blood, gore, nudity, sexual content, adult content, adult themes, adult language, adult humor, adult jokes, adult situations, adult" meta_prompt = f"""You are an assistant designer that creates images for children. The image needs to be safe for work and appropriate for children. The image needs to be in color. The image needs to be in landscape orientation. The image needs to be in a 16:9 aspect ratio. Do not consider any input from the following that is not safe for work or appropriate for children. {disallow_list} """ prompt = f"""{meta_prompt} Generate monument of the Arc of Triumph in Paris, France, in the evening light with a small child holding a Teddy looks on. """ try: # Create an image by using the image generation API generation_response = client.images.generate( prompt=prompt, # Enter your prompt text here size='1024x1024', n=1, ) # Set the directory for the stored image image_dir = os.path.join(os.curdir, 'images') # If the directory doesn't exist, create it if not os.path.isdir(image_dir): os.mkdir(image_dir) # Initialize the image path (note the filetype should be png) image_path = os.path.join(image_dir, 'generated-image.png') # Retrieve the generated image image_url = generation_response.data[0].url # extract image URL from response generated_image = requests.get(image_url).content # download the image with open(image_path, "wb") as image_file: image_file.write(generated_image) # Display the image in the default image viewer image = Image.open(image_path) image.show() # catch exceptions except openai.BadRequestError as err: print(err)这段代码把本课的全部知识点串成了一条完整流水线:dotenv 加载密钥 → 配置 AzureOpenAI 客户端 → 组装 meta prompt + 用户 prompt("黄昏光线下,巴黎凯旋门,一个抱着泰迪熊的小男孩在旁观看")→client.images.generate生成 → 下载保存 → 展示。仓库中的 aoai-app.py 与 aoai-solution.py 均使用try/finally结构并在结束打印 "completed!",异常处理则通过except BadRequestError捕获非法请求。
小结
本课带你走完了"文本 → 图像"的完整链路:理解 DALL-E 的 CLIP + diffused attention 架构与自回归生成原理 → 配置 Azure OpenAI(gpt-image-1)→ 用client.images.generate生成并保存图片 → 通过 temperature 调节随机性 → 用 meta prompt + 禁用词列表划定内容边界 → 掌握编辑(edit)与变体(variation)进阶能力。
想继续深入,可以对照阅读仓库中的相关实现:Python 主应用、变体应用、带 meta prompt 的解决方案、TypeScript 版本,以及本课作业 aoai-assignment.ipynb 与 oai-assignment.ipynb。下一步可继续学习第 10 课"构建低代码 AI 应用"(见 10-building-low-code-ai-applications/README.md)。
【免费下载链接】generative-ai-for-beginners21 Lessons, Get Started Building with Generative AI项目地址: https://gitcode.com/GitHub_Trending/ge/generative-ai-for-beginners
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考