> ## Documentation Index
> Fetch the complete documentation index at: https://hobbyist-e43fa225.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Use the image generation tool (preview) in Foundry Agent Service

> Generate images from text prompts with the image generation tool in Microsoft Foundry Agent Service. Configure agents, deploy models, and save output.

export const ZonePivot = ({group, options = [], defaultValue, label = "Choose an experience"}) => {
  const values = options.map(option => option.id);
  const optionKey = options.map(option => `${option.id}:${option.title}`).join("|");
  const [activePivot, setActivePivot] = useState(defaultValue || values[0]);
  const slugify = value => value.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
  const resolvePivot = () => {
    if (typeof window === "undefined") return defaultValue || values[0];
    const params = new URLSearchParams(window.location.search);
    const requested = params.get("pivots");
    if (requested) {
      const requestedIds = requested.split(",").map(value => value.trim()).filter(Boolean);
      const match = requestedIds.find(id => values.includes(id));
      if (match) return match;
    }
    const hash = window.location.hash.replace(/^#/, "");
    if (hash) {
      const match = options.find(option => option.id === hash || slugify(option.title) === hash);
      if (match) return match.id;
    }
    try {
      const stored = window.localStorage.getItem(`foundry-zone-pivot:${group}`);
      if (values.includes(stored)) return stored;
    } catch {
      return defaultValue || values[0];
    }
    return defaultValue || values[0];
  };
  const publishPivotChange = value => {
    if (typeof window === "undefined") return;
    window.dispatchEvent(new CustomEvent("foundry-zone-pivot-change", {
      detail: {
        group,
        value
      }
    }));
  };
  const syncTableOfContents = () => {
    if (typeof window === "undefined") return;
    window.requestAnimationFrame(() => {
      const toc = document.getElementById("table-of-contents-content");
      if (!toc) return;
      const links = Array.from(toc.querySelectorAll('a[href^="#"]'));
      for (const link of links) {
        const item = link.closest("li");
        const rawId = link.getAttribute("href")?.slice(1);
        if (!item || !rawId) continue;
        let id = rawId;
        try {
          id = decodeURIComponent(rawId);
        } catch {}
        item.style.display = document.getElementById(id) ? "" : "none";
      }
    });
  };
  useEffect(() => {
    const resolvedPivot = resolvePivot();
    setActivePivot(resolvedPivot);
    publishPivotChange(resolvedPivot);
    window.setTimeout(syncTableOfContents, 0);
  }, [group, defaultValue, values.join("|"), optionKey]);
  const selectPivot = value => {
    setActivePivot(value);
    if (typeof window !== "undefined") {
      try {
        window.localStorage.setItem(`foundry-zone-pivot:${group}`, value);
      } catch {}
      const url = new URL(window.location.href);
      const current = url.searchParams.get("pivots");
      const preserved = current ? current.split(",").map(id => id.trim()).filter(id => id && !values.includes(id)) : [];
      url.searchParams.set("pivots", [...preserved, value].join(","));
      window.history.replaceState(null, "", `${url.pathname}${url.search}${url.hash}`);
    }
    publishPivotChange(value);
    window.setTimeout(syncTableOfContents, 0);
  };
  if (options.length < 2) return null;
  return <div className="not-prose my-6 border-b border-slate-200 pb-3 dark:border-slate-800">
      <div className="mb-2 text-xs font-semibold uppercase tracking-wide text-slate-500 dark:text-slate-400">
        {label}
      </div>
      <div className="flex flex-wrap gap-2" role="tablist" aria-label={label}>
        {options.map(option => {
    const selected = option.id === activePivot;
    return <button key={option.id} type="button" role="tab" aria-selected={selected} onClick={() => selectPivot(option.id)} className={`rounded-md border px-3 py-1.5 text-sm font-medium transition ${selected ? "border-slate-900 bg-slate-900 text-white shadow-sm dark:border-slate-100 dark:bg-slate-100 dark:text-slate-950" : "border-slate-200 bg-white text-slate-700 hover:border-slate-400 hover:text-slate-950 dark:border-slate-700 dark:bg-slate-950 dark:text-slate-200 dark:hover:border-slate-500"}`}>
              {option.title}
            </button>;
  })}
      </div>
    </div>;
};

export const ZoneContent = ({group, value, options = [], values = [], defaultValue, children}) => {
  const optionKey = options.map(option => `${option.id}:${option.title}`).join("|");
  const [activePivot, setActivePivot] = useState(defaultValue || values[0]);
  const slugify = value => value.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
  const resolvePivot = () => {
    if (typeof window === "undefined") return defaultValue || values[0];
    const params = new URLSearchParams(window.location.search);
    const requested = params.get("pivots");
    if (requested) {
      const requestedIds = requested.split(",").map(value => value.trim()).filter(Boolean);
      const match = requestedIds.find(id => values.includes(id));
      if (match) return match;
    }
    const hash = window.location.hash.replace(/^#/, "");
    if (hash) {
      const match = options.find(option => option.id === hash || slugify(option.title) === hash);
      if (match) return match.id;
    }
    try {
      const stored = window.localStorage.getItem(`foundry-zone-pivot:${group}`);
      if (values.includes(stored)) return stored;
    } catch {
      return defaultValue || values[0];
    }
    return defaultValue || values[0];
  };
  useEffect(() => {
    setActivePivot(resolvePivot());
  }, [group, defaultValue, values.join("|"), optionKey]);
  useEffect(() => {
    const onPivotChange = event => {
      if (event.detail?.group === group && values.includes(event.detail.value)) {
        setActivePivot(event.detail.value);
      }
    };
    window.addEventListener("foundry-zone-pivot-change", onPivotChange);
    return () => window.removeEventListener("foundry-zone-pivot-change", onPivotChange);
  }, [group, values.join("|")]);
  if (activePivot !== value) return null;
  return <>{children}</>;
};

<Info>
  * The image generation tool requires the `gpt-image-1` model. See the [Azure OpenAI transparency note](../../../responsible-ai/openai/transparency-note) for limitations and responsible AI considerations.
  * You also need a compatible orchestrator model (`gpt-4o`, `gpt-4o-mini`, `gpt-4.1`, `gpt-4.1-mini`, `gpt-4.1-nano`, `o3`, or `gpt-5` series) deployed in the same Foundry project.
</Info>

The **image generation tool** in Microsoft Foundry Agent Service generates images from text prompts in conversations and multistep workflows. The agent's Foundry model orchestrates the image generation request and returns base64-encoded output that you can save to a file.

## Usage support

The following table shows SDK and setup support.

| Microsoft Foundry support | Python SDK | C# SDK | JavaScript SDK | Java SDK | REST API | Basic agent setup | Standard agent setup |
| ------------------------- | ---------- | ------ | -------------- | -------- | -------- | ----------------- | -------------------- |
| ✔️                        | ✔️         | ✔️     | ✔️             | ✔️       | ✔️       | ✔️                | ✔️                   |

## Prerequisites

* An Azure account with an active subscription.
* A Foundry project.
* A basic or standard agent environment. See [agent environment setup](../../../agents/environment-setup).
* Permissions to create and manage agent versions in the project.
* Two model deployments in the same Foundry project:
  * A compatible Azure OpenAI model deployment for the agent (for example, `gpt-4o`).
  * An image generation model deployment (`gpt-image-1`).

## Configure the image generation tool

1. Deploy your orchestrator model (for example, `gpt-4o`) to your Foundry project.
2. Deploy `gpt-image-1` to the same Foundry project.
3. Confirm your region and model support for image generation. See [Best practices for using tools in Microsoft Foundry Agent Service](/agents/tool-best-practice).

## Code examples

Before you start, install the latest SDK package. The .NET SDK is currently in preview. For package installation instructions, see the [quickstart](/get-started/get-started-code).

<ZonePivot group="csharp__java__python__rest-api__typescript" options={[{"id": "python", "title": "Python"}, {"id": "csharp", "title": "C#"}, {"id": "rest-api", "title": "REST API"}, {"id": "typescript", "title": "TypeScript"}, {"id": "java", "title": "Java"}]} defaultValue="python" />

<ZoneContent group="csharp__java__python__rest-api__typescript" value="python" options={[{"id": "python", "title": "Python"}, {"id": "csharp", "title": "C#"}, {"id": "rest-api", "title": "REST API"}, {"id": "typescript", "title": "TypeScript"}, {"id": "java", "title": "Java"}]} values={["python", "csharp", "rest-api", "typescript", "java"]} defaultValue="python">
  ## Create an agent with the image generation tool

  This sample creates an agent with the image generation tool, generates an image, and saves it to a file. Select **Prompt Agents** to use the Azure AI Projects SDK to create a server-side prompt agent, or **Hosted Agents** to use the Agent Framework [`FoundryChatClient`](/agents/responses-api) to build an ephemeral, in-process agent.

  <Tabs>
    <Tab title="Prompt Agents">
      ```python theme={null}
      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-4.1-mini",
              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}")
      ```
    </Tab>

    <Tab title="Hosted Agents">
      This sample uses [`FoundryChatClient`](/agents/responses-api) from the Microsoft Agent Framework and calls `get_image_generation_tool()` to attach the image generation tool. Install the package with `pip install agent-framework-foundry aiohttp`, set the `FOUNDRY_PROJECT_ENDPOINT` and `FOUNDRY_MODEL` environment variables, and sign in with `az login`.

      ```python theme={null}
      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())
      ```

      ### Expected output

      The tool returns base64-encoded image bytes, which the sample saves to disk; the model's text reply is also printed:

      ```console theme={null}
      Image saved to: /path/to/microsoft.png
      Agent: Here is the generated Microsoft logo image.
      ```

      For more about Agent Framework Foundry tool factories, see the [Foundry provider samples](https://github.com/microsoft/agent-framework/tree/main/python/samples/02-agents/providers/foundry).
    </Tab>
  </Tabs>
</ZoneContent>

<ZoneContent group="csharp__java__python__rest-api__typescript" value="csharp" options={[{"id": "python", "title": "Python"}, {"id": "csharp", "title": "C#"}, {"id": "rest-api", "title": "REST API"}, {"id": "typescript", "title": "TypeScript"}, {"id": "java", "title": "Java"}]} values={["python", "csharp", "rest-api", "typescript", "java"]} defaultValue="python">
  ## Sample for image generation in Azure.AI.Extensions.OpenAI

  In this example, you generate an image based on a simple prompt. The code in this example is synchronous. For an asynchronous example, see the [sample code](https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/ai/Azure.AI.Extensions.OpenAI/samples/Sample2_Image_Generation.md) example in the Azure SDK for .NET repository on GitHub.

  ```csharp theme={null}
  using System;
  using Azure.AI.Projects;
  using Azure.AI.Extensions.OpenAI;
  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-4.1-mini")
  {
  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);
      }
  }
  ```

  ### Expected output

  When you run the sample, you see the following output:

  ```console theme={null}
  Agent created (id: <agent-id>, name: myAgent, version: 1)
  Image downloaded and saved to: /path/to/newton.png
  Agent deleted
  ```
</ZoneContent>

<ZoneContent group="csharp__java__python__rest-api__typescript" value="rest-api" options={[{"id": "python", "title": "Python"}, {"id": "csharp", "title": "C#"}, {"id": "rest-api", "title": "REST API"}, {"id": "typescript", "title": "TypeScript"}, {"id": "java", "title": "Java"}]} values={["python", "csharp", "rest-api", "typescript", "java"]} defaultValue="python">
  ## Create an agent with the image generation tool

  Get an access token:

  ```bash theme={null}
  export AGENT_TOKEN=$(az account get-access-token --scope "https://ai.azure.com/.default" --query accessToken -o tsv)
  ```

  The following example creates an agent that uses the image generation tool.

  ```bash theme={null}
  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": "'$FOUNDRY_MODEL_DEPLOYMENT_NAME'",
        "tools": [
          {
            "type": "image_generation"
          }
        ],
        "instructions": "You are a creative assistant that generates images when requested. Please respond to image generation requests clearly and concisely."
      }
    }'
  ```

  ## Create a response

  ```bash theme={null}
  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: $IMAGE_GENERATION_MODEL_DEPLOYMENT_NAME" \
    -d '{
      "agent": {
        "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
    }'
  ```

  ### Expected output

  The response JSON includes an `image_generation_call` output item with a `result` field containing base64-encoded image data:

  ```json theme={null}
  {
    "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."
          }
        ]
      }
    ]
  }
  ```

  To extract and save the image, pipe the response through `jq` and `base64`:

  ```bash theme={null}
  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: $IMAGE_GENERATION_MODEL_DEPLOYMENT_NAME" \
    -d '{ ... }')

  echo "$RESPONSE" | jq -r '.output[] | select(.type=="image_generation_call") | .result' \
    | base64 --decode > generated_image.png
  ```
</ZoneContent>

<ZoneContent group="csharp__java__python__rest-api__typescript" value="typescript" options={[{"id": "python", "title": "Python"}, {"id": "csharp", "title": "C#"}, {"id": "rest-api", "title": "REST API"}, {"id": "typescript", "title": "TypeScript"}, {"id": "java", "title": "Java"}]} values={["python", "csharp", "rest-api", "typescript", "java"]} defaultValue="python">
  ## Create an agent with image generation tool

  This sample demonstrates how to create an AI agent with image generation capabilities by using the Azure AI Projects client. The agent generates images based on text prompts and saves them to files. For a JavaScript example, see the [sample code](https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/ai/ai-projects/samples/v2-beta/javascript/agents/tools/agentImageGeneration.js) in the Azure SDK for JavaScript repository on GitHub.

  ```typescript theme={null}
  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-4.1-mini",
      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: { 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);
  });
  ```

  ### Expected output

  When you run the sample, you see the following output:

  ```console theme={null}
  Agent created (id: <agent-id>, name: agent-image-generation, version: 1)
  Image downloaded and saved to: /path/to/microsoft.png
  ```
</ZoneContent>

<ZoneContent group="csharp__java__python__rest-api__typescript" value="java" options={[{"id": "python", "title": "Python"}, {"id": "csharp", "title": "C#"}, {"id": "rest-api", "title": "REST API"}, {"id": "typescript", "title": "TypeScript"}, {"id": "java", "title": "Java"}]} values={["python", "csharp", "rest-api", "typescript", "java"]} defaultValue="python">
  ## Use image generation in a Java agent

  Add the dependency to your `pom.xml`:

  ```xml theme={null}
  <dependency>
      <groupId>com.azure</groupId>
      <artifactId>azure-ai-agents</artifactId>
      <version>2.2.0</version>
  </dependency>
  ```

  ### Create an agent with image generation

  ```java theme={null}
  import com.azure.ai.agents.AgentsClient;
  import com.azure.ai.agents.AgentsClientBuilder;
  import com.azure.ai.agents.ResponsesClient;
  import com.azure.ai.agents.models.*;
  import com.azure.identity.DefaultAzureCredentialBuilder;
  import com.openai.models.responses.Response;
  import com.openai.models.responses.ResponseCreateParams;

  import java.util.Collections;

  public class ImageGenerationExample {
      public static void main(String[] args) {
          // 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();
          ResponsesClient responsesClient = builder.buildResponsesClient();

          // 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-4.1-mini")
              .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());

          // Create a response
          AgentReference agentReference = new AgentReference(agent.getName())
              .setVersion(agent.getVersion());

          Response response = responsesClient.createAzureResponse(
              new AzureCreateResponseOptions().setAgentReference(agentReference),
              ResponseCreateParams.builder()
                  .input("Generate an image of a sunset over a mountain range"));

          // The response output includes image_generation_call items with base64-encoded image data.
          // Extract and save the image using the response output items.
          System.out.println("Response status: " + response.status().map(Object::toString).orElse("unknown"));
          System.out.println("Output items: " + response.output().size());

          // Clean up
          agentsClient.deleteAgentVersion(agent.getName(), agent.getVersion());
      }
  }
  ```

  <Note>
    The `response.output()` list contains `image_generation_call` items with base64-encoded image data in the `result` field. Use `java.util.Base64.getDecoder().decode()` to convert the result to bytes and write them to a file.
  </Note>

  ### Expected output

  ```output theme={null}
  Agent created: image-gen-agent (version 1)
  Response status: completed
  Output items: 2
  ```
</ZoneContent>

## When to use the image generation tool

The image generation tool in Agent Service offers advantages over the Azure OpenAI Image API:

| Advantage       | Description                                                                   |
| --------------- | ----------------------------------------------------------------------------- |
| Streaming       | Display partial image outputs during generation to improve perceived latency. |
| Flexible inputs | Accept image file IDs as inputs, in addition to raw image bytes.              |

## Optional parameters

Customize image generation by specifying these optional parameters when you create the tool:

| Parameter            | Description                                                              |
| -------------------- | ------------------------------------------------------------------------ |
| `size`               | Image size. One of `1024x1024`, `1024x1536`, `1536x1024`, or `auto`.     |
| `quality`            | Image quality. One of `low`, `medium`, `high`, or `auto`.                |
| `background`         | Background type. One of `transparent`, `opaque`, or `auto`.              |
| `output_format`      | Output format. One of `png`, `webp`, or `jpeg`.                          |
| `output_compression` | Compression level for `webp` and `jpeg` output (0-100).                  |
| `moderation`         | Moderation level for the generated image. One of `auto` or `low`.        |
| `partial_images`     | Number of partial images to generate in streaming mode (0-3).            |
| `input_image_mask`   | Optional mask for inpainting. Provide `image_url` (base64) or `file_id`. |

<Note>
  Image generation time varies based on the `quality` setting and prompt complexity. For time-sensitive applications, consider using `quality: "low"` or enabling `partial_images` for streaming.
</Note>

Use the Responses API if you want to:

* Build conversational image experiences with GPT Image.
* Stream partial image results during generation for a smoother user experience.

## Write effective text-to-image prompts

Effective prompts produce better images. Describe the subject, visual style, and composition you want. Use action words like "draw," "create," or "edit" to guide the model's output.

Content filtering can block image generation if the service detects unsafe content in your prompt. For more information, see [Guardrails and controls overview](../../../guardrails/guardrails-overview).

<Tip>
  For a thorough look at how you can tweak your text prompts to generate different kinds of images, see [Image prompt engineering techniques](/models/gpt-4-v-prompt-engineering).
</Tip>

## Verify tool execution

Use either of these approaches to confirm that image generation ran successfully:

* In the response payload, look for an output item with `type` set to `image_generation_call`.
* In the Foundry portal, open tracing/debug for your run to confirm the tool call and inspect inputs and outputs.

When image generation succeeds, the response includes an `image_generation_call` output item with a `result` field containing base64-encoded image data.

If you see only text output and no `image_generation_call` item, the request might not be routed to image generation. Review the troubleshooting section.

## Troubleshooting

| Issue                           | Cause                                 | Resolution                                                                                                                                                        |
| ------------------------------- | ------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Image generation fails          | Missing deployment                    | Verify both the orchestrator model (for example, `gpt-4o`) and `gpt-image-1` deployments exist in the same Foundry project.                                       |
| Image generation fails          | Missing or incorrect header           | Verify the header `x-ms-oai-image-generation-deployment` is present on the Responses request and matches your image generation deployment name.                   |
| Agent uses wrong deployment     | Model name misconfiguration           | Confirm the orchestrator model name in your agent definition differs from the image generation deployment name.                                                   |
| Prompt doesn't produce an image | Content filtering blocked the request | Check content filtering logs. See [Guardrails and controls overview](../../../guardrails/guardrails-overview) for guidelines on acceptable prompts.               |
| Tool not available              | Regional or model limitation          | Confirm the image generation tool is available in your region and with your orchestrator model. See [Best practices for using tools](/agents/tool-best-practice). |
| Generated image has low quality | Prompt lacks detail                   | Provide more specific and detailed prompts describing the desired image style, composition, and elements.                                                         |
| Image generation times out      | Large or complex image request        | Simplify the prompt or increase timeout settings. Consider breaking complex requests into multiple simpler ones.                                                  |
| Unexpected image content        | Ambiguous prompt                      | Refine your prompt to be more specific. Include negative prompts to exclude unwanted elements.                                                                    |

## Related content

* [Best practices for using tools in Microsoft Foundry Agent Service](/agents/tool-best-practice)
* [Image generation in Azure OpenAI](/models/dall-e)
* [Responses API in Azure OpenAI](/models/responses)
* [Guardrails and controls overview](../../../guardrails/guardrails-overview)
