共用方式為


快速入門:在 Microsoft Foundry 模型中使用 Azure OpenAI 生成影像

請參考本指南,開始使用 Python 呼叫 Microsoft Foundry 模型中的 Azure OpenAI 影像生成 REST API。

先決條件

設定

擷取金鑰和端點

若要成功呼叫 Azure OpenAI API,您需要有關 Azure OpenAI 資源的下列資訊:

變數 名稱 價值觀
端點 api_base 端點值位於 Azure 入口網站中資源的 [金鑰和端點]。 你也可以透過 Foundry 入口網站的 部署 頁面找到該端點。 範例端點為:https://docs-test-001.openai.azure.com/
鑰匙 api_key 金鑰值同樣也位於 Azure 入口網站中資源的 [金鑰和端點]。 Azure 會為您的資源產生兩個金鑰。 您可以使用任何一者。

移至您在 Azure 入口網站中的資源。 在瀏覽窗格中,選取 [資源管理] 下的 [金鑰和端點]。 複製端點值和存取金鑰值。 您可以使用 KEY 1KEY 2 值。 隨時持有兩個金鑰可讓您安全地輪替和重新產生金鑰,而不會造成服務中斷。

螢幕擷取畫面顯示 Azure 入口網站中 Azure OpenAI 資源的 [金鑰和端點] 頁面。

環境變數

為您的金鑰和端點建立及指派永續性環境變數。

這很重要

我們建議使用適用於 Azure 資源的受控識別搭配 Microsoft Entra ID 驗證,以避免使用在雲端執行的應用程式儲存認證。

請謹慎使用 API 金鑰。 請勿在程式碼中直接包含 API 金鑰,且切勿公開張貼金鑰。 如果使用 API 金鑰,請安全地將它們儲存在 Azure 金鑰保存庫、定期輪替金鑰,並使用角色型存取控制和網路存取限制來限制對 Azure 金鑰保存庫 的存取。 如需在應用程式中安全地使用 API 金鑰的詳細資訊,請參閱 使用 Azure Key Vault 的 API 金鑰

如需 AI 服務安全性的詳細資訊,請參閱驗證對 Azure AI 服務的要求

setx AZURE_OPENAI_API_KEY "REPLACE_WITH_YOUR_KEY_VALUE_HERE" 
setx AZURE_OPENAI_ENDPOINT "REPLACE_WITH_YOUR_ENDPOINT_HERE" 

建立新的 Python 應用程式

建立命名為 quickstart.py 的新 Python 檔案。 在您慣用的編輯器或整合式開發環境 (IDE) 中,開啟新檔案。

  1. quickstart.py 的內容取代為下列程式碼。 將 prompt 的值變更為您慣用的文字。 也設定 deployment 為部署 GPT-image-1 模型時所選擇的部署名稱。

    import os
    import requests
    import base64
    from PIL import Image
    from io import BytesIO
    
    # set environment variables
    endpoint = os.getenv("AZURE_OPENAI_ENDPOINT")
    subscription_key = os.getenv("AZURE_OPENAI_API_KEY")
    
    deployment = "gpt-image-1" # the name of your GPT-image-1 deployment
    api_version = "2025-04-01-preview" # or later version
    
    def decode_and_save_image(b64_data, output_filename):
      image = Image.open(BytesIO(base64.b64decode(b64_data)))
      image.show()
      image.save(output_filename)
    
    def save_all_images_from_response(response_data, filename_prefix):
      for idx, item in enumerate(response_data['data']):
        b64_img = item['b64_json']
        filename = f"{filename_prefix}_{idx+1}.png"
        decode_and_save_image(b64_img, filename)
        print(f"Image saved to: '{filename}'")
    
    base_path = f'openai/deployments/{deployment}/images'
    params = f'?api-version={api_version}'
    
    generation_url = f"{endpoint}{base_path}/generations{params}"
    generation_body = {
      "prompt": "girl falling asleep",
      "n": 1,
      "size": "1024x1024",
      "quality": "medium",
      "output_format": "png"
    }
    generation_response = requests.post(
      generation_url,
      headers={
        'Api-Key': subscription_key,
        'Content-Type': 'application/json',
      },
      json=generation_body
    ).json()
    save_all_images_from_response(generation_response, "generated_image")
    
    # In addition to generating images, you can edit them.
    edit_url = f"{endpoint}{base_path}/edits{params}"
    edit_body = {
      "prompt": "girl falling asleep",
      "n": 1,
      "size": "1024x1024",
      "quality": "medium"
    }
    files = {
      "image": ("generated_image_1.png", open("generated_image_1.png", "rb"), "image/png"),
      # You can use a mask to specify which parts of the image you want to edit.
      # The mask must be the same size as the input image.
      # "mask": ("mask.png", open("mask.png", "rb"), "image/png"),
    }
    edit_response = requests.post(
      edit_url,
      headers={'Api-Key': subscription_key},
      data=edit_body,
      files=files
    ).json()
    save_all_images_from_response(edit_response, "edited_image")
    

    指令碼會進行同步影像生成 API 呼叫。

    這很重要

    切記,完成時請從程式碼中移除金鑰,且切勿公開發佈您的金鑰。 在生產環境中,請運用安全的方式來儲存和存取您的登入資訊。 如需詳細資訊,請參閱 Azure Key Vault

  2. 使用 python 命令執行應用程式:

    python quickstart.py
    

    請稍候片刻以取得回應。

輸出

成功影像產生 API 呼叫的輸出看起來像下列範例。 url 欄位包含您可以用來下載所產生影像的 URL。 URL 的使用中狀態會維持 24 個小時。

{ 
    "created": 1698116662, 
    "data": [ 
        { 
            "url": "<URL_to_generated_image>",
            "revised_prompt": "<prompt_that_was_used>" 
        }
    ]
} 

影像 API 包含內容審核篩選器。 如果該服務將您的提示辨識為有害內容,則不會產生影像。 如需詳細資訊,請參閱 內容篩選。 如需錯誤回應的範例,請參閱 映像產生作指南

系統會傳回 Failed 的作業狀態,且訊息中的 error.code 值會設定為 contentFilter。 以下為範例:

{
    "created": 1698435368,
    "error":
    {
        "code": "contentFilter",
        "message": "Your task failed as a result of our safety system."
    }
}

產生的影像本身也可能受到篩選。 在此情況下,錯誤訊息會設定為 Generated image was filtered as a result of our safety system.。 以下為範例:

{
    "created": 1698435368,
    "error":
    {
        "code": "contentFilter",
        "message": "Generated image was filtered as a result of our safety system."
    }
}

清理資源

如果您想要清除和移除 Azure OpenAI 資源,則可以刪除資源或資源群組。 刪除資源群組也會刪除與其相關聯的任何其他資源。

後續步驟

使用本指南開始使用適用於 Python 的 Azure OpenAI SDK 生成影像。

程式庫原始程式碼 | 套件 | 範例

先決條件

設定

擷取金鑰和端點

若要成功呼叫 Azure OpenAI API,您需要有關 Azure OpenAI 資源的下列資訊:

變數 名稱 價值觀
端點 api_base 端點值位於 Azure 入口網站中資源的 [金鑰和端點]。 您也可以透過 Microsoft Foundry 入口網站的 部署 頁面找到該端點。 範例端點為:https://docs-test-001.openai.azure.com/
鑰匙 api_key 金鑰值同樣也位於 Azure 入口網站中資源的 [金鑰和端點]。 Azure 會為您的資源產生兩個金鑰。 您可以使用任何一者。

移至您在 Azure 入口網站中的資源。 在瀏覽窗格中,選取 [資源管理] 下的 [金鑰和端點]。 複製端點值和存取金鑰值。 您可以使用 KEY 1KEY 2 值。 隨時持有兩個金鑰可讓您安全地輪替和重新產生金鑰,而不會造成服務中斷。

螢幕擷取畫面顯示 Azure 入口網站中 Azure OpenAI 資源的 [金鑰和端點] 頁面。

環境變數

為您的金鑰和端點建立及指派永續性環境變數。

這很重要

我們建議使用適用於 Azure 資源的受控識別搭配 Microsoft Entra ID 驗證,以避免使用在雲端執行的應用程式儲存認證。

請謹慎使用 API 金鑰。 請勿在程式碼中直接包含 API 金鑰,且切勿公開張貼金鑰。 如果使用 API 金鑰,請安全地將它們儲存在 Azure 金鑰保存庫、定期輪替金鑰,並使用角色型存取控制和網路存取限制來限制對 Azure 金鑰保存庫 的存取。 如需在應用程式中安全地使用 API 金鑰的詳細資訊,請參閱 使用 Azure Key Vault 的 API 金鑰

如需 AI 服務安全性的詳細資訊,請參閱驗證對 Azure AI 服務的要求

setx AZURE_OPENAI_API_KEY "REPLACE_WITH_YOUR_KEY_VALUE_HERE" 
setx AZURE_OPENAI_ENDPOINT "REPLACE_WITH_YOUR_ENDPOINT_HERE" 

安裝 Python SDK

開啟命令提示字元,並瀏覽至您的專案資料夾。 使用下列命令安裝 OpenAI Python SDK:

pip install openai

也請安裝下列程式庫:

pip install requests
pip install pillow 

使用 DALL-E 生成影像

建立一個新的 Python 檔案 quickstart.py。 在您慣用的編輯器或 IDE 中加以開啟。

quickstart.py 的內容取代為下列程式碼。

from openai import AzureOpenAI
import os
import requests
from PIL import Image
import json

client = AzureOpenAI(
    api_version="2024-02-01",  
    api_key=os.environ["AZURE_OPENAI_API_KEY"],  
    azure_endpoint=os.environ['AZURE_OPENAI_ENDPOINT']
)

result = client.images.generate(
    model="dalle3", # the name of your DALL-E 3 deployment
    prompt="a close-up of a bear walking throughthe forest",
    n=1
)

json_response = json.loads(result.model_dump_json())

# 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 = json_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()
  1. 在適當的欄位中輸入您的端點 URL 和金鑰。
  2. prompt 的值變更為您慣用的文字。
  3. model 的值變更為您部署的 DALL-E 3 模型的名稱。

這很重要

切記,完成時請從程式碼中移除金鑰,且切勿公開發佈您的金鑰。 在生產環境中,請運用安全的方式來儲存和存取您的登入資訊。 如需詳細資訊,請參閱 Azure Key Vault

使用 python 命令執行應用程式:

python quickstart.py

請稍候片刻以取得回應。

輸出

Azure OpenAI 會將輸出影像儲存在指定目錄中的 generated_image.png 檔案中。 然後,指令碼也會在預設的影像檢視器中顯示該影像。

影像 API 包含內容審核篩選器。 如果該服務將您的提示辨識為有害內容,則不會產生影像。 如需詳細資訊,請參閱 內容篩選

清理資源

如果您想要清除和移除 Azure OpenAI 資源,則可以刪除資源或資源群組。 刪除資源群組也會刪除與其相關聯的任何其他資源。

後續步驟

使用本指南開始使用適用於 C# 的 Azure OpenAI SDK 生成影像。

程式庫原始程式碼 | 套件 (NuGet) | 範例

先決條件

Microsoft Entra ID 必要條件

針對具有 Microsoft Entra ID 的建議無金鑰驗證,您需要:

  • 安裝用於無密鑰驗證的 Azure CLI 以進行 Microsoft Entra ID 的認證。
  • Cognitive Services User 角色指派給您的使用者帳戶。 您可以在 Azure 入口網站中,在 [存取控制 (IAM)]> [新增角色指派] 下指派角色。

設定

  1. 建立新的資料夾 vision-quickstart ,並使用下列命令移至快速入門資料夾:

    mkdir vision-quickstart && cd vision-quickstart
    
  2. 使用下列命令建立新的主控台應用程式:

    dotnet new console
    
  3. 使用 dotnet add package 命令安裝 OpenAI .NET 用戶端連結庫:

    dotnet add package Azure.AI.OpenAI --version 1.0.0-beta.6
    
  4. 如需使用 Microsoft Entra ID 推薦的無密鑰驗證,請安裝 Azure.Identity 套件:

    dotnet add package Azure.Identity
    
  5. 如需使用 Microsoft Entra ID 的建議 無密鑰驗證,請使用下列命令登入 Azure:

    az login
    

擷取資源資訊

您需要擷取下列資訊,以向 Azure OpenAI 資源驗證您的應用程式:

變數名稱 價值觀
AZURE_OPENAI_ENDPOINT 在 Azure 入口網站查看資源時,您可以在 [金鑰和端點] 區段中找到此值。
AZURE_OPENAI_DEPLOYMENT_NAME 此值會對應至您在部署模型時為部署選擇的自訂名稱。 您可以在 Azure 入口網站 中的資源管理找到此值。

深入瞭解 無金鑰驗證設定環境變數

執行快速入門

本快速入門中的範例程式代碼會針對建議的無密鑰驗證使用 Microsoft Entra 識別碼。 如果您想要使用 API 金鑰,可以將 DefaultAzureCredential 物件取代為 AzureKeyCredential 物件。

AzureOpenAIClient openAIClient = new AzureOpenAIClient(new Uri(endpoint), new DefaultAzureCredential()); 

若要執行快速啟動,請遵循下列步驟:

  1. Program.cs 的內容替換為以下代碼,並將佔位元值更新為您自己的值。

    using Azure;
    using Azure.AI.OpenAI;
    using OpenAI.Images;
    using static System.Environment;
    
    string endpoint = Environment.GetEnvironmentVariable("AZURE_OPENAI_ENDPOINT") ?? "https://<your-resource-name>.openai.azure.com/";
    string key = Environment.GetEnvironmentVariable("AZURE_OPENAI_API_KEY") ?? "<your-key>";
    
    // Use the recommended keyless credential instead of the AzureKeyCredential credential.
    AzureOpenAIClient openAIClient = new AzureOpenAIClient(new Uri(endpoint), new DefaultAzureCredential()); 
    //AzureOpenAIClient openAIClient = new AzureOpenAIClient(new Uri(endpoint), new AzureKeyCredential(key));
    
    // This must match the custom deployment name you chose for your model
    ImageClient chatClient = openAIClient.GetImageClient("dalle-3");
    
    var imageGeneration = await chatClient.GenerateImageAsync(
            "a happy monkey sitting in a tree, in watercolor",
            new ImageGenerationOptions()
            {
                Size = GeneratedImageSize.W1024xH1024
            }
        );
    
    Console.WriteLine(imageGeneration.Value.ImageUri);
    
  2. 使用 dotnet run Visual Studio 頂端的 命令或執行按鈕執行應用程式:

    dotnet run
    

輸出

生成的影像 URL 會列印至主控台。

<SAS URL>

備註

影像 API 包含內容審核篩選器。 如果服務將提示辨識為有害內容,則就不會傳回產生的影像。 如需詳細資訊,請參閱內容篩選條件文章。

清理資源

如果您想要清除和移除 Azure OpenAI 資源,可以刪除資源。 刪除資源之前,您必須先刪除任何已部署的模型。

後續步驟

使用本指南開始使用適用於 Java 的 Azure OpenAI SDK 生成影像。

程式庫原始程式碼 | 成品 (Maven) | 範例

先決條件

Microsoft Entra ID 必要條件

針對具有 Microsoft Entra ID 的建議無金鑰驗證,您需要:

  • 安裝用於無密鑰驗證的 Azure CLI 以進行 Microsoft Entra ID 的認證。
  • Cognitive Services User 角色指派給您的使用者帳戶。 您可以在 Azure 入口網站中,在 [存取控制 (IAM)]> [新增角色指派] 下指派角色。

設定

  1. 建立新的資料夾 vision-quickstart ,並使用下列命令移至快速入門資料夾:

    mkdir vision-quickstart && cd vision-quickstart
    
  2. 安裝 Apache Maven。 然後執行 mvn -v 以確認安裝成功。

  3. 在專案的根目錄中建立新 pom.xml 檔案,並將下列程式碼複製到其中:

    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
         <modelVersion>4.0.0</modelVersion>
         <groupId>com.azure.samples</groupId>
         <artifactId>quickstart-dall-e</artifactId>
         <version>1.0.0-SNAPSHOT</version>
         <build>
             <sourceDirectory>src</sourceDirectory>
             <plugins>
             <plugin>
                 <artifactId>maven-compiler-plugin</artifactId>
                 <version>3.7.0</version>
                 <configuration>
                 <source>1.8</source>
                 <target>1.8</target>
                 </configuration>
             </plugin>
             </plugins>
         </build>
         <dependencies>    
             <dependency>
                 <groupId>com.azure</groupId>
                 <artifactId>azure-ai-openai</artifactId>
                 <version>1.0.0-beta.3</version>
             </dependency>
             <dependency>
                 <groupId>com.azure</groupId>
                 <artifactId>azure-core</artifactId>
                 <version>1.53.0</version>
             </dependency>
             <dependency>
                 <groupId>com.azure</groupId>
                 <artifactId>azure-identity</artifactId>
                 <version>1.15.1</version>
             </dependency>
             <dependency>
                 <groupId>org.slf4j</groupId>
                 <artifactId>slf4j-simple</artifactId>
                 <version>1.7.9</version>
             </dependency>
         </dependencies>
     </project>
    
  4. 安裝 Azure OpenAI SDK 和相依性。

    mvn clean dependency:copy-dependencies
    
  5. 如需使用 Microsoft Entra ID 的建議 無密鑰驗證,請使用下列命令登入 Azure:

    az login
    

擷取資源資訊

您需要擷取下列資訊,以向 Azure OpenAI 資源驗證您的應用程式:

變數名稱 價值觀
AZURE_OPENAI_ENDPOINT 在 Azure 入口網站查看資源時,您可以在 [金鑰和端點] 區段中找到此值。
AZURE_OPENAI_DEPLOYMENT_NAME 此值會對應至您在部署模型時為部署選擇的自訂名稱。 您可以在 Azure 入口網站 中的資源管理找到此值。

深入瞭解 無金鑰驗證設定環境變數

執行應用程式

本快速入門中的範例程式代碼會針對建議的無密鑰驗證使用 Microsoft Entra 識別碼。 如果您想要使用 API 金鑰,可以將 DefaultAzureCredential 物件取代為 AzureKeyCredential 物件。

OpenAIAsyncClient client = new OpenAIClientBuilder()
    .endpoint(endpoint)
    .credential(new DefaultAzureCredentialBuilder().build())
    .buildAsyncClient();

遵循下列步驟來建立新的主控台應用程式,以進行語音辨識。

  1. 在相同的專案根目錄中,建立名為 Quickstart.java 的新檔案。

  2. 將下列程式代碼複製到 Quickstart.java

    import com.azure.ai.openai.OpenAIAsyncClient;
    import com.azure.ai.openai.OpenAIClientBuilder;
    import com.azure.ai.openai.models.ImageGenerationOptions;
    import com.azure.ai.openai.models.ImageLocation;
    import com.azure.core.credential.AzureKeyCredential;
    import com.azure.core.models.ResponseError;
    
    import java.util.concurrent.TimeUnit;
    
    public class Quickstart {
    
        public static void main(String[] args) throws InterruptedException {
    
            String endpoint = System.getenv("AZURE_OPENAI_ENDPOINT");
    
            // Use the recommended keyless credential instead of the AzureKeyCredential credential.
    
            OpenAIAsyncClient client = new OpenAIClientBuilder()
                .endpoint(endpoint)
                .credential(new DefaultAzureCredentialBuilder().build())
                .buildAsyncClient();
    
            ImageGenerationOptions imageGenerationOptions = new ImageGenerationOptions(
                "A drawing of the Seattle skyline in the style of Van Gogh");
            client.getImages(imageGenerationOptions).subscribe(
                images -> {
                    for (ImageLocation imageLocation : images.getData()) {
                        ResponseError error = imageLocation.getError();
                        if (error != null) {
                            System.out.printf("Image generation operation failed. Error code: %s, error message: %s.%n",
                                error.getCode(), error.getMessage());
                        } else {
                            System.out.printf(
                                "Image location URL that provides temporary access to download the generated image is %s.%n",
                                imageLocation.getUrl());
                        }
                    }
                },
                error -> System.err.println("There was an error getting images." + error),
                () -> System.out.println("Completed getImages."));
    
            // The .subscribe() creation and assignment isn't a blocking call.
            // The thread sleeps so the program does not end before the send operation is complete. 
            // Use .block() instead of .subscribe() for a synchronous call.
            TimeUnit.SECONDS.sleep(10);
        }
    }
    
  3. 執行新的主控台應用程式以產生映像:

    javac Quickstart.java -cp ".;target\dependency\*"
    java -cp ".;target\dependency\*" Quickstart
    

輸出

生成的影像 URL 會列印至主控台。

Image location URL that provides temporary access to download the generated image is <SAS URL>.
Completed getImages.

備註

影像 API 包含內容審核篩選器。 如果服務將提示辨識為有害內容,則就不會傳回產生的影像。 如需詳細資訊,請參閱內容篩選條件文章。

清理資源

如果您想要清除和移除 Azure OpenAI 資源,可以刪除資源。 刪除資源之前,您必須先刪除任何已部署的模型。

後續步驟

使用本指南開始使用適用於 JavaScript 的 Azure OpenAI SDK 生成影像。

參考文件 | 原始碼 | 套件(npm) | 範例

先決條件

Microsoft Entra ID 必要條件

針對具有 Microsoft Entra ID 的建議無金鑰驗證,您需要:

  • 安裝用於無密鑰驗證的 Azure CLI 以進行 Microsoft Entra ID 的認證。
  • Cognitive Services User 角色指派給您的使用者帳戶。 您可以在 Azure 入口網站中,在 [存取控制 (IAM)]> [新增角色指派] 下指派角色。

設定

  1. 建立新的資料夾 image-quickstart ,並使用下列命令移至快速入門資料夾:

    mkdir image-quickstart && cd image-quickstart
    
  2. 使用下列命令建立 package.json

    npm init -y
    
  3. 使用以下指令安裝適用於 JavaScript 的 OpenAI 客戶端庫:

    npm install openai
    
  4. 若要設定建議的無密碼驗證:

    npm install @azure/identity
    

擷取資源資訊

您需要擷取下列資訊,以向 Azure OpenAI 資源驗證您的應用程式:

變數名稱 價值觀
AZURE_OPENAI_ENDPOINT 在 Azure 入口網站查看資源時,您可以在 [金鑰和端點] 區段中找到此值。
AZURE_OPENAI_DEPLOYMENT_NAME 此值會對應至您在部署模型時為部署選擇的自訂名稱。 您可以在 Azure 入口網站 中的資源管理找到此值。

深入瞭解 無金鑰驗證設定環境變數

謹慎

若要搭配 SDK 使用建議的無密鑰驗證,請確定 AZURE_OPENAI_API_KEY 未設定環境變數。

使用 DALL-E 生成影像

  1. 使用下列程式代碼,建立 index.js 檔案。

    const { AzureOpenAI } = require("openai");
    const { 
        DefaultAzureCredential, 
        getBearerTokenProvider 
    } = require("@azure/identity");
    
    // You will need to set these environment variables or edit the following values
    const endpoint = process.env.AZURE_OPENAI_ENDPOINT || "Your endpoint";
    
    // Required Azure OpenAI deployment name and API version
    const apiVersion = process.env.OPENAI_API_VERSION || "2024-07-01";
    const deploymentName = process.env.AZURE_OPENAI_DEPLOYMENT_NAME || "dall-e-3";
    
    // The prompt to generate images from
    const prompt = "a monkey eating a banana";
    const numberOfImagesToGenerate = 1;
    
    // keyless authentication    
    const credential = new DefaultAzureCredential();
    const scope = "https://cognitiveservices.azure.com/.default";
    const azureADTokenProvider = getBearerTokenProvider(credential, scope);
    
    function getClient(): AzureOpenAI {
      return new AzureOpenAI({
        endpoint,
        azureADTokenProvider,
        apiVersion,
        deployment: deploymentName,
      });
    }
    async function main() {
      console.log("== Image Generation ==");
    
      const client = getClient();
    
      const results = await client.images.generate({
        prompt,
        size: "1024x1024",
        n: numberOfImagesToGenerate,
        model: "",
        style: "vivid", // or "natural"
      });
    
      for (const image of results.data) {
        console.log(`Image generation result URL: ${image.url}`);
      }
    }
    
    main().catch((err) => {
      console.error("The sample encountered an error:", err);
    });
    
  2. 使用下列命令登入 Azure:

    az login
    
  3. 執行 JavaScript 檔案。

    node index.js
    

輸出

生成的影像 URL 會列印至主控台。

== Batch Image Generation ==
Image generation result URL: <SAS URL>
Image generation result URL: <SAS URL>

備註

影像 API 包含內容審核篩選器。 如果服務將提示辨識為有害內容,則就不會傳回產生的影像。 如需詳細資訊,請參閱內容篩選條件文章。

清理資源

如果您想要清除和移除 Azure OpenAI 資源,可以刪除資源。 刪除資源之前,您必須先刪除任何已部署的模型。

後續步驟

使用本指南開始使用適用於 JavaScript 的 Azure OpenAI SDK 生成影像。

參考文件 | 原始碼 | 套件(npm) | 範例

先決條件

Microsoft Entra ID 必要條件

針對具有 Microsoft Entra ID 的建議無金鑰驗證,您需要:

  • 安裝用於無密鑰驗證的 Azure CLI 以進行 Microsoft Entra ID 的認證。
  • Cognitive Services User 角色指派給您的使用者帳戶。 您可以在 Azure 入口網站中,在 [存取控制 (IAM)]> [新增角色指派] 下指派角色。

設定

  1. 建立新的資料夾 image-quickstart ,並使用下列命令移至快速入門資料夾:

    mkdir image-quickstart && cd image-quickstart
    
  2. 使用下列命令建立 package.json

    npm init -y
    
  3. 請使用下列命令將 package.json 更新為 ECMAScript。

    npm pkg set type=module
    
  4. 使用以下指令安裝適用於 JavaScript 的 OpenAI 客戶端庫:

    npm install openai
    
  5. 若要設定建議的無密碼驗證:

    npm install @azure/identity
    

擷取資源資訊

您需要擷取下列資訊,以向 Azure OpenAI 資源驗證您的應用程式:

變數名稱 價值觀
AZURE_OPENAI_ENDPOINT 在 Azure 入口網站查看資源時,您可以在 [金鑰和端點] 區段中找到此值。
AZURE_OPENAI_DEPLOYMENT_NAME 此值會對應至您在部署模型時為部署選擇的自訂名稱。 您可以在 Azure 入口網站 中的資源管理找到此值。

深入瞭解 無金鑰驗證設定環境變數

謹慎

若要搭配 SDK 使用建議的無密鑰驗證,請確定 AZURE_OPENAI_API_KEY 未設定環境變數。

使用 DALL-E 生成影像

  1. 使用下列程式代碼,建立 index.ts 檔案。

    import { AzureOpenAI } from "openai";
    import { 
        DefaultAzureCredential, 
        getBearerTokenProvider 
    } from "@azure/identity";
    
    // You will need to set these environment variables or edit the following values
    const endpoint = process.env.AZURE_OPENAI_ENDPOINT || "Your endpoint";
    
    // Required Azure OpenAI deployment name and API version
    const apiVersion = process.env.OPENAI_API_VERSION || "2024-07-01";
    const deploymentName = process.env.AZURE_OPENAI_DEPLOYMENT_NAME || "dall-e-3";
    
    // keyless authentication    
    const credential = new DefaultAzureCredential();
    const scope = "https://cognitiveservices.azure.com/.default";
    const azureADTokenProvider = getBearerTokenProvider(credential, scope);
    
    function getClient(): AzureOpenAI {
      return new AzureOpenAI({
        endpoint,
        azureADTokenProvider,
        apiVersion,
        deployment: deploymentName,
      });
    }
    async function main() {
      console.log("== Image Generation ==");
    
      const client = getClient();
    
      const results = await client.images.generate({
        prompt,
        size: "1024x1024",
        n: numberOfImagesToGenerate,
        model: "",
        style: "vivid", // or "natural"
      });
    
      for (const image of results.data) {
        console.log(`Image generation result URL: ${image.url}`);
      }
    }
    
    main().catch((err) => {
      console.error("The sample encountered an error:", err);
    });
    
  2. 建立檔案 tsconfig.json 以轉譯 TypeScript 程式代碼,並複製 ECMAScript 的下列程式代碼。

    {
        "compilerOptions": {
          "module": "NodeNext",
          "target": "ES2022", // Supports top-level await
          "moduleResolution": "NodeNext",
          "skipLibCheck": true, // Avoid type errors from node_modules
          "strict": true // Enable strict type-checking options
        },
        "include": ["*.ts"]
    }
    
  3. 從 TypeScript 轉譯為 JavaScript。

    tsc
    
  4. 使用下列命令登入 Azure:

    az login
    
  5. 使用下列命令執行程式碼:

    node index.js
    

輸出

生成的影像 URL 會列印至主控台。

== Batch Image Generation ==
Image generation result URL: <SAS URL>
Image generation result URL: <SAS URL>

備註

影像 API 包含內容審核篩選器。 如果服務將提示辨識為有害內容,則就不會傳回產生的影像。 如需詳細資訊,請參閱內容篩選條件文章。

清理資源

如果您想要清除和移除 Azure OpenAI 資源,可以刪除資源。 刪除資源之前,您必須先刪除任何已部署的模型。

後續步驟

使用本指南開始使用適用於 Go 的 Azure OpenAI SDK 生成影像。

程式庫原始程式碼 | 套件 | 範例

先決條件

Microsoft Entra ID 必要條件

針對具有 Microsoft Entra ID 的建議無金鑰驗證,您需要:

  • 安裝用於無密鑰驗證的 Azure CLI 以進行 Microsoft Entra ID 的認證。
  • Cognitive Services User 角色指派給您的使用者帳戶。 您可以在 Azure 入口網站中,在 [存取控制 (IAM)]> [新增角色指派] 下指派角色。

設定

  1. 建立新的資料夾 dall-e-quickstart ,並使用下列命令移至快速入門資料夾:

    mkdir dall-e-quickstart && cd dall-e-quickstart
    
  2. 如需使用 Microsoft Entra ID 的建議 無密鑰驗證,請使用下列命令登入 Azure:

    az login
    

擷取資源資訊

您需要擷取下列資訊,以向 Azure OpenAI 資源驗證您的應用程式:

變數名稱 價值觀
AZURE_OPENAI_ENDPOINT 在 Azure 入口網站查看資源時,您可以在 [金鑰和端點] 區段中找到此值。
AZURE_OPENAI_DEPLOYMENT_NAME 此值會對應至您在部署模型時為部署選擇的自訂名稱。 您可以在 Azure 入口網站 中的資源管理找到此值。

深入瞭解 無金鑰驗證設定環境變數

執行快速入門

本快速入門中的範例程式代碼會針對建議的無密鑰驗證使用 Microsoft Entra 識別碼。 如果您要使用 API 金鑰,可以將 實作 NewDefaultAzureCredential 取代為 NewKeyCredential

azureOpenAIEndpoint := os.Getenv("AZURE_OPENAI_ENDPOINT")
credential, err := azidentity.NewDefaultAzureCredential(nil)
client, err := azopenai.NewClient(azureOpenAIEndpoint, credential, nil)

若要執行範例:

  1. 建立名為 quickstart.go 的新檔案。 將下列程式代碼複製到 quickstart.go 檔案。

     package main
    
    import (
    	"context"
    	"fmt"
    	"net/http"
    	"os"
    	"log"
    
    	"github.com/Azure/azure-sdk-for-go/sdk/ai/azopenai"
    	"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
    	"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
    )
    
    func main() {
    	azureOpenAIEndpoint := os.Getenv("AZURE_OPENAI_ENDPOINT")
    	modelDeploymentID := "dall-e-3"
    
    	credential, err := azidentity.NewDefaultAzureCredential(nil)
    	if err != nil {
    		log.Printf("ERROR: %s", err)
    		return
    	}
    
    	client, err := azopenai.NewClient(
    		azureOpenAIEndpoint, credential, nil)
    	if err != nil {
    		log.Printf("ERROR: %s", err)
    		return
    	}
    
    	resp, err := client.GetImageGenerations(context.TODO(), azopenai.ImageGenerationOptions{
    		Prompt:         to.Ptr("A painting of a cat in the style of Dali."),
    		ResponseFormat: to.Ptr(azopenai.ImageGenerationResponseFormatURL),
    		DeploymentName: to.Ptr(modelDeploymentID),
    	}, nil)
    
    	if err != nil {
    		// Implement application specific error handling logic.
    		log.Printf("ERROR: %s", err)
    		return
    	}
    
    	for _, generatedImage := range resp.Data {
    		// The underlying type for the generatedImage is determined by the value of
    		// ImageGenerationOptions.ResponseFormat. 
    		// In this example we use `azopenai.ImageGenerationResponseFormatURL`,
    		// so the underlying type will be ImageLocation.
    
    		resp, err := http.Head(*generatedImage.URL)
    
    		if err != nil {
    			// Implement application specific error handling logic.
    			log.Printf("ERROR: %s", err)
    			return
    		}
    
    		fmt.Fprintf(os.Stderr, "Image generated, HEAD request on URL returned %d\nImage URL: %s\n", resp.StatusCode, *generatedImage.URL)
    	}
    }
    
  2. 執行下列命令以建立新的 Go 模組:

     go mod init quickstart.go
    
  3. 執行 go mod tidy 以安裝必要的相依性:

    go mod tidy
    
  4. 執行下列命令以執行範例:

     go run quickstart.go
    

輸出

生成的影像 URL 會列印至主控台。

Image generated, HEAD request on URL returned 200
Image URL: <SAS URL>

備註

影像 API 包含內容審核篩選器。 如果服務將提示辨識為有害內容,則就不會傳回產生的影像。 如需詳細資訊,請參閱內容篩選條件文章。

清理資源

如果您想要清除和移除 Azure OpenAI 資源,則可以刪除資源或資源群組。 刪除資源群組也會刪除與其相關聯的任何其他資源。

後續步驟

請參考本指南,以使用 PowerShell 開始呼叫 Microsoft Foundry 模型的 Azure OpenAI 影像生成 API。

先決條件

Microsoft Entra ID 必要條件

針對具有 Microsoft Entra ID 的建議無金鑰驗證,您需要:

  • 安裝用於無密鑰驗證的 Azure CLI 以進行 Microsoft Entra ID 的認證。
  • Cognitive Services User 角色指派給您的使用者帳戶。 您可以在 Azure 入口網站中,在 [存取控制 (IAM)]> [新增角色指派] 下指派角色。

擷取資源資訊

您需要擷取下列資訊,以向 Azure OpenAI 資源驗證您的應用程式:

變數名稱 價值觀
AZURE_OPENAI_ENDPOINT 在 Azure 入口網站查看資源時,您可以在 [金鑰和端點] 區段中找到此值。
AZURE_OPENAI_DEPLOYMENT_NAME 此值會對應至您在部署模型時為部署選擇的自訂名稱。 您可以在 Azure 入口網站 中的資源管理找到此值。

深入瞭解 無金鑰驗證設定環境變數

產生影像

  1. 如需使用 Microsoft Entra ID 的建議 無密鑰驗證,請使用下列命令登入 Azure:

    az login
    
  2. 建立名為 quickstart.ps1的新 PowerShell 檔案。 然後,以您慣用的編輯器或 IDE 加以開啟。

  3. quickstart.ps1 的內容取代為以下程式碼。 在適當的欄位中輸入您的端點 URL 和金鑰。 將 prompt 的值變更為您慣用的文字。

     # Azure OpenAI metadata variables
     $openai = @{
         api_base    = $Env:AZURE_OPENAI_ENDPOINT 
         api_version = '2023-06-01-preview' # This can change in the future.
     }
    
     # Use the recommended keyless authentication via bearer token.
     $headers = [ordered]@{
         #'api-key' = $Env:AZURE_OPENAI_API_KEY
         'Authorization' = "Bearer $($Env:DEFAULT_AZURE_CREDENTIAL_TOKEN)"
     }
    
     # Text to describe image
     $prompt = 'A painting of a dog'
    
     # Adjust these values to fine-tune completions
     $body = [ordered]@{
         prompt = $prompt
         size   = '1024x1024'
         n      = 1
     } | ConvertTo-Json
    
     # Call the API to generate the image and retrieve the response
     $url = "$($openai.api_base)/openai/images/generations:submit?api-version=$($openai.api_version)"
    
     $submission = Invoke-RestMethod -Uri $url -Headers $headers -Body $body -Method Post -ContentType 'application/json' -ResponseHeadersVariable submissionHeaders
    
     $operation_location = $submissionHeaders['operation-location'][0]
     $status = ''
     while ($status -ne 'succeeded') {
         Start-Sleep -Seconds 1
         $response = Invoke-RestMethod -Uri $operation_location -Headers $headers
         $status   = $response.status
     }
    
     # Set the directory for the stored image
     $image_dir = Join-Path -Path $pwd -ChildPath 'images'
    
     # If the directory doesn't exist, create it
     if (-not(Resolve-Path $image_dir -ErrorAction Ignore)) {
         New-Item -Path $image_dir -ItemType Directory
     }
    
     # Initialize the image path (note the filetype should be png)
     $image_path = Join-Path -Path $image_dir -ChildPath 'generated_image.png'
    
     # Retrieve the generated image
     $image_url = $response.result.data[0].url  # extract image URL from response
     $generated_image = Invoke-WebRequest -Uri $image_url -OutFile $image_path  # download the image
     return $image_path
    

    這很重要

    針對生產環境,請使用安全的方式來儲存和存取您的認證,例如 使用 Azure Key Vault 的 PowerShell 秘密管理。 如需認證安全性的詳細資訊,請參閱此 安全性 文章。

  4. 使用 PowerShell 執行指令碼:

    ./quickstart.ps1
    

    指令碼會迴圈直到產生的映射就緒為止。

輸出

PowerShell 會向 Azure OpenAI 要求影像,並將輸出影像儲存在您指定目錄的 generated_image.png 檔案中。 為了方便起見,該檔案的完整路徑會在指令碼結尾傳回。

影像 API 包含內容審核篩選器。 如果該服務將您的提示辨識為有害內容,則不會產生影像。 如需詳細資訊,請參閱 內容篩選

清理資源

如果您想要清除和移除 Azure OpenAI 資源,則可以刪除資源或資源群組。 刪除資源群組也會刪除與其相關聯的任何其他資源。

後續步驟

請使用本指南,開始使用 Microsoft Foundry 在瀏覽器中使用 Azure OpenAI 生成影像。

先決條件

前往鑄造廠

瀏覽 Foundry 並以與你的 Azure OpenAI 資源相關憑證登入。 在登入工作流程期間 (或之後),選取適當的目錄、Azure 訂用帳戶和 Azure OpenAI 資源。

從 Foundry 登陸頁面,建立或選擇一個新專案。 瀏覽至左側導覽的 [模型 + 端點] 頁面。 選取 [部署模型],然後從清單中選擇其中一個 DALL-E 模型。 完成部署程序。

在模型的頁面上,選取 [在遊樂場中開啟]

試用影像產生

透過 [影像遊樂場] 以無程式碼方法開始探索 Azure OpenAI 功能。 在文字方塊中輸入您的影像提示字元,然後選取 [產生]。 當 AI 產生的影像準備就緒時,它會出現在頁面上。

備註

影像 API 包含內容審核篩選器。 如果 Azure OpenAI 將提示辨識為有害內容,則就不會傳回產生的影像。 如需詳細資訊,請參閱 內容篩選

在 [影像遊樂場] 中,您也可以檢視根據設定預先填入的 Python 和 cURL 程式碼範例。 選取頁面頂端附近的 [檢視程式碼]。 您可以使用此程式碼來撰寫能完成相同工作的應用程式。

清理資源

如果您想要清除和移除 Azure OpenAI 資源,則可以刪除資源或資源群組。 刪除資源群組也會刪除與其相關聯的任何其他資源。

後續步驟