重要
- イメージ生成ツールには、
gpt-image-1モデルが必要です。 制限事項と責任ある AI に関する考慮事項については、Azure OpenAI の透明性に関するメモを参照してください。 - また、同じ Foundry プロジェクトに配置された互換性のあるオーケストレーター モデルも必要です。 リージョンとモデル別のツールのサポートを参照してください。
Microsoft Foundry Agent Service の image 生成ツールは、会話やマルチステップ ワークフローのテキスト プロンプトから画像を生成します。 エージェントの Foundry モデルは、イメージ生成要求を調整し、ファイルに保存できる base64 でエンコードされた出力を返します。
GitHub Copilotなどのコーディング エージェントを使用する場合、Microsoft Foundry Skill は、モデルとプロジェクトの要件を検証し、イメージ生成ツールの呼び出しをエージェント ワークフローに追加するのに役立ちます。
前提 条件
アクティブなサブスクリプションを持つAzure アカウント。
Foundry プロジェクト。
基本または標準のエージェント環境。 エージェント環境のセットアップを参照してください。
エージェント のバージョンを作成および管理するための Foundry プロジェクトの Foundry ユーザー ロール。
重要
Foundry RBAC ロールの名前が最近変更されました。 Foundry User, Foundry Owner, Foundry Account Owner、および Foundry Project Manager は、以前は、AZURE AI ユーザー、Azure AI 所有者、Azure AI アカウント所有者、および AZURE AI Project Manager という名前でした。 名前の変更がロールアウトされている間、以前の名前が表示される場合があります。ロール ID とコア アクセス許可は、名前の変更によって変更されません。
gpt-image-1を使用するための承認。 モデルをデプロイする前に、GPT イメージ モデルへのアクセスを申請します。同じ Foundry プロジェクト内の 2 つのモデル デプロイ:
- エージェントの互換性のあるAzure OpenAI モデルのデプロイ (例:
gpt-5)。 - サポートされているリージョンでのイメージ生成モデルのデプロイ (
gpt-image-1)。
- エージェントの互換性のあるAzure OpenAI モデルのデプロイ (例:
使用サポート
次の表に、SDK とセットアップのサポートを示します。
| Microsoft Foundry のサポート | Python SDK | C# SDK | JavaScript SDK | Java SDK | REST API | 基本的なエージェントのセットアップ | 標準エージェントのセットアップ |
|---|---|---|---|---|---|---|---|
| ✔️ | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ |
イメージ生成ツールを構成する
- オーケストレーター モデル (
gpt-5など) を Foundry プロジェクトにデプロイします。 -
gpt-image-1を同じ Foundry プロジェクトに配置します。 - イメージ生成のリージョンとモデルのサポートを確認します。 「 Foundry Agent Service Microsoft でツールを使用するためのベスト プラクティス」を参照>。
コード例
ランタイムを使用し、選択した言語セクションでコマンドをインストールします。 .NET SDK は現在プレビュー段階です。 一般的な SDK のセットアップについては、 クイック スタートを参照してください。
イメージ生成ツールを使用してエージェントを作成する
このサンプルでは、イメージ生成ツールを使用してエージェントを作成し、イメージを生成してファイルに保存します。 Azure AI Projects SDK を使用してサーバー側プロンプト エージェントを作成する場合は Prompt Agents を選択します。エージェント フレームワーク を使用してエフェメラルなインプロセス エージェントを作成するには、FoundryChatClient を選択します。
prompt-agent サンプルには Python 3.10 以降を使用してください。 その依存関係をインストールします。
python -m pip install azure-ai-projects azure-identity
エージェントに指示を促す
import base64
import os
from azure.identity import DefaultAzureCredential
from azure.ai.projects import AIProjectClient
from azure.ai.projects.models import PromptAgentDefinition, ImageGenTool
# Format: "https://resource_name.ai.azure.com/api/projects/project_name"
PROJECT_ENDPOINT = "your_project_endpoint"
IMAGE_MODEL = "gpt-image-1"
# Create clients to call Foundry API
project = AIProjectClient(
endpoint=PROJECT_ENDPOINT,
credential=DefaultAzureCredential(),
)
openai = project.get_openai_client()
# Create an agent with the image generation tool
agent = project.agents.create_version(
agent_name="agent-image-generation",
definition=PromptAgentDefinition(
model="gpt-5",
instructions="Generate images based on user prompts.",
tools=[ImageGenTool(model=IMAGE_MODEL, quality="low", size="1024x1024")],
),
description="Agent for image generation.",
)
print(f"Agent created (id: {agent.id}, name: {agent.name}, version: {agent.version})")
# Generate an image using the agent
response = openai.responses.create(
input="Generate an image of the Microsoft logo.",
extra_headers={
"x-ms-oai-image-generation-deployment": IMAGE_MODEL,
},
extra_body={"agent_reference": {"name": agent.name, "type": "agent_reference"}},
)
# Clean up the agent
project.agents.delete_version(agent_name=agent.name, agent_version=agent.version)
# Extract and save the generated image
image_data = [output.result for output in response.output if output.type == "image_generation_call"]
if image_data and image_data[0]:
file_path = os.path.abspath("microsoft.png")
with open(file_path, "wb") as f:
f.write(base64.b64decode(image_data[0]))
print(f"Image saved to: {file_path}")
ホスト型エージェント
このサンプルでは、Microsoft Agent Framework から FoundryChatClient を使用し、get_image_generation_tool() を呼び出してイメージ生成ツールをアタッチします。
pip install agent-framework-foundry aiohttpでパッケージをインストールし、FOUNDRY_PROJECT_ENDPOINTとFOUNDRY_MODEL環境変数を設定し、az loginでサインインします。
import asyncio
import base64
import os
from agent_framework import Agent
from agent_framework.foundry import FoundryChatClient
from azure.identity import AzureCliCredential
IMAGE_MODEL = "gpt-image-1"
async def main() -> None:
agent = Agent(
client=FoundryChatClient(credential=AzureCliCredential()),
instructions="Generate images based on user prompts.",
tools=[
FoundryChatClient.get_image_generation_tool(
model=IMAGE_MODEL,
quality="low",
size="1024x1024",
)
],
)
result = await agent.run("Generate an image of the Microsoft logo.")
# Extract and save the generated image from the raw response.
for output in result.raw_representation.output:
if output.type == "image_generation_call":
file_path = os.path.abspath("microsoft.png")
with open(file_path, "wb") as f:
f.write(base64.b64decode(output.result))
print(f"Image saved to: {file_path}")
print(f"Agent: {result.text}")
if __name__ == "__main__":
asyncio.run(main())
予期される出力
このツールは base64 でエンコードされたイメージ バイトを返します。このバイトは、サンプルによってディスクに保存されます。モデルのテキスト応答も出力されます。
Image saved to: /path/to/microsoft.png
Agent: Here is the generated Microsoft logo image.
Agent Framework Foundry ツール ファクトリの詳細については、 Foundry プロバイダーのサンプルを参照してください。
Azureでのイメージ生成のサンプル。Ai。Extensions.OpenAI
この例では、単純なプロンプトに基づいてイメージを生成します。 この例のコードは同期です。 非同期の例については、GitHubのリポジトリのAzure SDKのサンプル コードの例.NET参照してください。
.NET 8 SDK 以降を使用します。 必要なパッケージをプロジェクトに追加します。
dotnet add package Azure.AI.Projects
dotnet add package Azure.AI.Extensions.OpenAI
dotnet add package Azure.Identity
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using Azure.AI.Projects;
using Azure.AI.Extensions.OpenAI;
using Azure.Core;
using Azure.Core.Pipeline;
using Azure.Identity;
// Format: "https://resource_name.ai.azure.com/api/projects/project_name"
var projectEndpoint = "your_project_endpoint";
var imageModel = "gpt-image-1";
// Create the AI Project client with custom header policy
AIProjectClientOptions projectOptions = new();
projectOptions.AddPolicy(new HeaderPolicy(imageModel), PipelinePosition.PerCall);
// Create the AI Project client
AIProjectClient projectClient = new(
endpoint: new Uri(projectEndpoint),
tokenProvider: new DefaultAzureCredential(),
options: projectOptions
);
// Use the client to create the versioned agent object.
// To generate images, we need to provide agent with the ImageGenerationTool
// when creating this tool. The ImageGenerationTool parameters include
// the image generation model, image quality and resolution.
// Supported image generation models include gpt-image-1.
DeclarativeAgentDefinition agentDefinition = new(model: "gpt-5")
{
Instructions = "Generate images based on user prompts.",
Tools = {
ResponseTool.CreateImageGenerationTool(
model: imageModel,
quality: ImageGenerationToolQuality.Low,
size:ImageGenerationToolSize.W1024xH1024
)
}
};
AgentVersion agentVersion = projectClient.AgentAdministrationClient.CreateAgentVersion(
agentName: "myAgent",
options: new(agentDefinition));
ProjectOpenAIClient openAIClient = projectClient.GetProjectOpenAIClient();
ProjectResponsesClient responseClient = openAIClient.GetProjectResponsesClientForAgent(new AgentReference(name: agentVersion.Name));
ResponseResult response = responseClient.CreateResponse("Generate parody of Newton with apple.");
// Parse the ResponseResult object and save the generated image.
foreach (ResponseItem item in response.OutputItems)
{
if (item is ImageGenerationCallResponseItem imageItem)
{
File.WriteAllBytes("newton.png", imageItem.ImageResultBytes.ToArray());
Console.WriteLine($"Image downloaded and saved to: {Path.GetFullPath("newton.png")}");
}
}
// Clean up resources by deleting the Agent.
projectClient.AgentAdministrationClient.DeleteAgentVersion(agentName: agentVersion.Name, agentVersion: agentVersion.Version);
// To use image generation, provide the custom header to web requests,
// which contain the model deployment name, for example:
// `x-ms-oai-image-generation-deployment: gpt-image-1`.
// To implement it, create a custom header policy.
internal class HeaderPolicy(string image_deployment) : PipelinePolicy
{
private const string image_deployment_header = "x-ms-oai-image-generation-deployment";
public override void Process(PipelineMessage message, IReadOnlyList<PipelinePolicy> pipeline, int currentIndex)
{
message.Request.Headers.Add(image_deployment_header, image_deployment);
ProcessNext(message, pipeline, currentIndex);
}
public override async ValueTask ProcessAsync(PipelineMessage message, IReadOnlyList<PipelinePolicy> pipeline, int currentIndex)
{
// Add your desired header name and value
message.Request.Headers.Add(image_deployment_header, image_deployment);
await ProcessNextAsync(message, pipeline, currentIndex);
}
}
予期される出力
サンプルを実行すると、次の出力が表示されます。
Agent created (id: <agent-id>, name: myAgent, version: 1)
Image downloaded and saved to: /path/to/newton.png
Agent deleted
イメージ生成ツールを使用してエージェントを作成する
Azure CLI、curl、jq、およびbase64をサポートする--decode コマンドで Bash 互換シェルを使用します。 要求を実行する前に、 FOUNDRY_PROJECT_ENDPOINT を設定します。
アクセス トークンを取得します。
export AGENT_TOKEN=$(az account get-access-token --scope "https://ai.azure.com/.default" --query accessToken -o tsv)
次の例では、イメージ生成ツールを使用するエージェントを作成します。
curl -X POST "$FOUNDRY_PROJECT_ENDPOINT/agents?api-version=v1" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $AGENT_TOKEN" \
-d '{
"name": "image-gen-agent",
"description": "Test agent for image generation capabilities",
"definition": {
"kind": "prompt",
"model": "gpt-5",
"tools": [
{
"type": "image_generation"
}
],
"instructions": "You are a creative assistant that generates images when requested. Please respond to image generation requests clearly and concisely."
}
}'
応答を作成する
curl -X POST "$FOUNDRY_PROJECT_ENDPOINT/openai/v1/responses" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $AGENT_TOKEN" \
-H "x-ms-oai-image-generation-deployment: gpt-image-1" \
-d '{
"agent_reference": {
"type": "agent_reference",
"name": "image-gen-agent"
},
"input": [{
"type": "message",
"role": "user",
"content": [
{
"type": "input_text",
"text": "Please generate small image of a sunset over a mountain lake."
}
]
}],
"stream": false
}'
予期される出力
応答 JSON には、base64 でエンコードされた画像データを含むimage_generation_call フィールドを含むresult出力項目が含まれています。
{
"id": "resp_<id>",
"status": "completed",
"output": [
{
"type": "image_generation_call",
"result": "<base64-encoded-image-data>",
"status": "completed"
},
{
"type": "message",
"role": "assistant",
"content": [
{
"type": "output_text",
"text": "Here is the image of a sunset over a mountain lake."
}
]
}
]
}
画像を抽出して保存するには、 jq と base64を通じて応答をパイプ処理します。
RESPONSE=$(curl -s -X POST "$FOUNDRY_PROJECT_ENDPOINT/openai/v1/responses" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $AGENT_TOKEN" \
-H "x-ms-oai-image-generation-deployment: gpt-image-1" \
-d '{ ... }')
echo "$RESPONSE" | jq -r '.output[] | select(.type=="image_generation_call") | .result' \
| base64 --decode > generated_image.png
REST エージェントをクリーンアップする
生成されたイメージを保存した後、エージェントを削除します。
curl --request DELETE \
--url "$FOUNDRY_PROJECT_ENDPOINT/agents/image-gen-agent?api-version=v1" \
-H "Authorization: Bearer $AGENT_TOKEN"
イメージ生成ツールを使用してエージェントを作成する
このサンプルでは、Azure AI Projects クライアントを使用して、画像生成機能を備えた AI エージェントを作成する方法を示します。 エージェントは、テキスト プロンプトに基づいてイメージを生成し、ファイルに保存します。 JavaScript の例については、GitHubの JavaScript リポジトリのAzure SDKのサンプル コードを参照してください。
Node.js 22 以降を使用します。 必要なパッケージをインストールします。
npm install @azure/ai-projects @azure/identity
import { DefaultAzureCredential } from "@azure/identity";
import { AIProjectClient } from "@azure/ai-projects";
import * as fs from "fs";
import * as path from "path";
import { fileURLToPath } from "url";
// Format: "https://resource_name.ai.azure.com/api/projects/project_name"
const PROJECT_ENDPOINT = "your_project_endpoint";
const IMAGE_MODEL = "gpt-image-1";
export async function main(): Promise<void> {
// Create clients to call Foundry API
const project = new AIProjectClient(PROJECT_ENDPOINT, new DefaultAzureCredential());
const openai = project.getOpenAIClient();
// Create Agent with image generation tool
const agent = await project.agents.createVersion("agent-image-generation", {
kind: "prompt",
model: "gpt-5",
instructions: "Generate images based on user prompts",
tools: [
{
type: "image_generation",
quality: "low",
size: "1024x1024",
},
],
});
console.log(`Agent created (id: ${agent.id}, name: ${agent.name}, version: ${agent.version})`);
// Generate image using the agent
const response = await openai.responses.create(
{
input: "Generate an image of Microsoft logo.",
},
{
body: { agent_reference: { name: agent.name, type: "agent_reference" } },
headers: { "x-ms-oai-image-generation-deployment": IMAGE_MODEL },
},
);
// Extract and save the generated image
const imageData = response.output?.filter((output) => output.type === "image_generation_call");
if (imageData && imageData.length > 0 && imageData[0].result) {
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const filename = "microsoft.png";
const filePath = path.join(__dirname, filename);
// Decode base64 and save to file
const imageBuffer = Buffer.from(imageData[0].result, "base64");
fs.writeFileSync(filePath, imageBuffer);
console.log(`Image downloaded and saved to: ${path.resolve(filePath)}`);
} else {
console.log("No image data found in the response.");
}
// Clean up resources
await project.agents.deleteVersion(agent.name, agent.version);
}
main().catch((err) => {
console.error("The sample encountered an error:", err);
});
予期される出力
サンプルを実行すると、次の出力が表示されます。
Agent created (id: <agent-id>, name: agent-image-generation, version: 1)
Image downloaded and saved to: /path/to/microsoft.png
Java エージェントでイメージ生成を使用する
JDK 17 以降と Maven 3.8 以降を使用します。 依存関係を pom.xmlに追加します。
Java クライアントは現在、応答の作成時に必要なx-ms-oai-image-generation-deployment ヘッダーを公開していません。 Javaを使用してエージェント定義を作成し、この記事の REST プロシージャを使用してエージェントを呼び出し、生成されたイメージを取得します。
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-ai-agents</artifactId>
<version>2.4.0</version>
</dependency>
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-identity</artifactId>
<version>1.18.4</version>
</dependency>
イメージ生成を使用してエージェントを作成する
import com.azure.ai.agents.AgentsClient;
import com.azure.ai.agents.AgentsClientBuilder;
import com.azure.ai.agents.models.*;
import com.azure.identity.DefaultAzureCredentialBuilder;
import java.util.Collections;
public class ImageGenerationExample {
public static void main(String[] args) throws Exception {
// Format: "https://resource_name.ai.azure.com/api/projects/project_name"
String projectEndpoint = "your_project_endpoint";
String imageModel = "gpt-image-1";
AgentsClientBuilder builder = new AgentsClientBuilder()
.credential(new DefaultAzureCredentialBuilder().build())
.endpoint(projectEndpoint);
AgentsClient agentsClient = builder.buildAgentsClient();
// Create image generation tool with model, quality, and size
ImageGenTool imageGenTool = new ImageGenTool()
.setModel(ImageGenToolModel.fromString(imageModel))
.setQuality(ImageGenToolQuality.LOW)
.setSize(ImageGenToolSize.fromString("1024x1024"));
// Create agent with image generation tool
PromptAgentDefinition agentDefinition = new PromptAgentDefinition("gpt-5")
.setInstructions("You are a creative assistant that can generate images based on descriptions.")
.setTools(Collections.singletonList(imageGenTool));
AgentVersionDetails agent = agentsClient.createAgentVersion("image-gen-agent", agentDefinition);
System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion());
// Clean up
agentsClient.deleteAgentVersion(agent.getName(), agent.getVersion());
}
}
予期される出力
Agent created: image-gen-agent (version 1)
イメージ生成ツールを使用する場合
エージェントが会話またはマルチステップ ワークフローの一部としてテキスト プロンプトから画像を生成する必要がある場合は、イメージ生成ツールを使用します。 Azure OpenAI Image API を直接使用して、画像の編集、マスク、または部分イメージ ストリーミングを行います。
省略可能なパラメーター
ツールの作成時に次の省略可能なパラメーターを指定して、イメージの生成をカスタマイズします。
| パラメーター | 説明 |
|---|---|
size |
画像のサイズ。
1024x1024、1024x1536、1536x1024、またはautoのいずれか。 |
quality |
画質。
low、medium、high、またはautoのいずれか。 |
background |
背景の種類。
transparent、opaque、またはautoのいずれか。 |
output_format |
出力形式。
png、webp、またはjpegのいずれか。 |
output_compression |
webpおよびjpeg出力の圧縮レベル (0 から 100)。 |
moderation |
生成されたイメージのモデレーション レベル。
autoまたはlowのいずれか。 |
メモ
イメージの生成時間は、 quality 設定とプロンプトの複雑さによって異なります。 時間の影響を受けやすいアプリケーションの場合は、 quality: "low"の使用を検討してください。
次の場合は、Responses API を使用します。
- GPT Image を使用して会話型イメージ エクスペリエンスを構築します。
- マルチステップ エージェント ワークフローにイメージ生成を含める。
効果的なテキストから画像へのプロンプトを記述する
効果的なプロンプトにより、より良い画像が生成されます。 目的の件名、視覚スタイル、およびコンポジションについて説明します。 モデルの出力をガイドするには、"描画"、"作成"、"編集" などのアクションワードを使用します。
サービスがプロンプトで安全でないコンテンツを検出した場合、コンテンツ フィルタリングによって画像の生成がブロックされる可能性があります。 詳細については、「 ガードレールとコントロールの概要」を参照してください。
ヒント
テキスト プロンプトを調整してさまざまな種類の画像を生成する方法の詳細については、「 イメージ プロンプト エンジニアリングの手法」を参照してください。
ツールの実行を確認する
イメージの生成が正常に実行されたことを確認するには、次のいずれかの方法を使用します。
- 応答ペイロードで、
typeがimage_generation_callに設定されている出力項目を探します。 - Foundry ポータルで、実行のトレース/デバッグを開き、ツールの呼び出しを確認し、入力と出力を検査します。
画像の生成が成功すると、応答には、base64 でエンコードされた画像データを含むimage_generation_call フィールドを含むresult出力項目が含まれます。
テキスト出力のみが表示され、 image_generation_call 項目がない場合、要求がイメージ生成にルーティングされない可能性があります。 トラブルシューティングのセクションを確認します。
トラブルシューティング
| 問題 | 原因 | 解決方法 |
|---|---|---|
| イメージの生成に失敗する | デプロイが見つからない | オーケストレーター モデル ( gpt-5 など) と gpt-image-1 デプロイの両方が同じ Foundry プロジェクトに存在するかどうかを確認します。 |
| イメージの生成に失敗する | ヘッダーが見つからないか、正しくない | 応答要求にヘッダー x-ms-oai-image-generation-deployment が存在し、イメージ生成デプロイ名と一致することを確認します。 |
| エージェントが誤ったデプロイを使用している | モデル名設定の誤り | エージェント定義のオーケストレーター モデル名がイメージ生成デプロイ名と異なることを確認します。 |
| プロンプトでイメージが生成されない | コンテンツ のフィルター処理によって要求がブロックされました | コンテンツ フィルタリング ログを確認します。 受け入れ可能なプロンプトのガイドラインについては、 Guardrails とコントロールの概要 に関するページを参照してください。 |
| ツールは使用できません | リージョンまたはモデルの制限 | イメージ生成ツールがリージョンとオーケストレーター モデルで使用できるかどうかを確認します。 ツールの使用に関するベスト プラクティスを参照してください。 |
| 生成された画像の品質が低い | プロンプトに詳細がない | 目的の画像のスタイル、構成、および要素について説明する、より具体的で詳細なプロンプトを提供します。 |
| イメージの生成がタイムアウトする | 大規模または複雑なイメージ要求 | プロンプトを簡略化するか、タイムアウト設定を増やします。 複雑な要求を複数の単純な要求に分割することを検討してください。 |
| 予期しない画像の内容 | あいまいなプロンプト | プロンプトをより具体的に絞り込みます。 不要な要素を除外するには、負のプロンプトを含めます。 |