本文說明如何利用 Responses API 為 Foundry 模型(如 Microsoft AI、Deepseek 和 Grok 模型)產生文字回應。 欲了解支援 Responses API 的完整 Foundry 模型清單,請參見 支援的 Foundry 模型。
先決條件
要在您的應用程式中使用部署的模型來使用 Responses API,您需要:
使用 AI 模型入門套件
本文中的程式碼片段來自 AI 模型入門套件。 利用這套入門套件快速開始設定所需的完整雲端基礎設施和代碼,並使用穩定的 OpenAI 函式庫與 Responses API 來呼叫 Foundry Models。
使用 Responses API 來產生文字
請使用本節的程式碼來呼叫 Foundry 模型的回應 API。 在程式碼範例中,你建立客戶端來接收模型,然後發送基本請求。
小提示
當你在 Foundry 入口網站部署模型時,你會為它指派一個部署名稱。 在 API 呼叫的參數中使用這個部署名稱(而非模型目錄 ID)。
-
Python(編程語言)
-
C#
-
JavaScript
-
爪哇島
-
前進
安裝函式庫,包括 Azure Identity 用戶端函式庫:
pip install azure-identity
pip install openai
請使用以下程式碼在 project 路徑中配置 OpenAI 用戶端物件,指定你的部署,並產生回應。
from azure.identity import DefaultAzureCredential, get_bearer_token_provider
from openai import OpenAI
project_endpoint = "https://YOUR-RESOURCE-NAME.services.ai.azure.com/api/projects/YOUR_PROJECT_NAME"
# Build the base URL: project_endpoint + /openai/v1 (no api-version needed)
base_url = project_endpoint.rstrip("/") + "/openai/v1"
# Use get_bearer_token_provider for automatic token refresh
credential = DefaultAzureCredential()
client = OpenAI(
base_url=base_url,
api_key=get_bearer_token_provider(credential, "https://ai.azure.com/.default"),
)
response = client.responses.create(
model="DeepSeek-V3.1", # Replace with your deployment name, not the model ID
input="What are the top 3 benefits of cloud computing? Be concise.",
max_output_tokens=500,
)
print(response.model_dump_json(indent=2))
安裝 Azure Identity 客戶端函式庫:
dotnet add package Azure.Identity
dotnet add package OpenAI
請使用以下程式碼在 project 路徑中配置 OpenAI 用戶端物件,指定你的部署,並產生回應。
using Azure.Identity;
using OpenAI;
using OpenAI.Responses;
var deploymentName = "DeepSeek-V3.1"; // Replace with your deployment name, not the model ID
var project_endpoint = "https://YOUR-RESOURCE-NAME.services.ai.azure.com/api/projects/YOUR_PROJECT_NAME";
// Get EntraID token for keyless auth
var credential = new DefaultAzureCredential();
var token = await credential.GetTokenAsync(
new Azure.Core.TokenRequestContext(["https://ai.azure.com/.default"])
);
// Standard OpenAI client — no AzureOpenAI wrapper (no api-version needed with /v1 path)
var baseUrl = project_endpoint.TrimEnd('/') + "/openai/v1";
var client = new OpenAIClient(
new ApiKeyCredential(token.Token),
new OpenAIClientOptions { Endpoint = new Uri(baseUrl) });
var responseClient = client.GetResponsesClient(deploymentName);
var result = await responseClient.CreateResponseAsync(new CreateResponseOptions(
[ResponseItem.CreateUserMessageItem("What are the top 3 benefits of cloud computing? Be concise.")])
{ MaxOutputTokenCount = 500 }
);
Console.WriteLine($"Response: {result.Value.GetOutputText()}");
Console.WriteLine($"Status: {result.Value.Status}");
Console.WriteLine($"Output tokens: {result.Value.Usage.OutputTokenCount}");
在使用 DefaultAzureCredential 之前,先安裝 Azure Identity 用戶端函式庫:
npm install @azure/identity
npm install openai
請使用以下程式碼在 project 路徑中配置 OpenAI 用戶端物件,指定你的部署,並產生回應。
import OpenAI from "openai";
import { DefaultAzureCredential } from "@azure/identity";
async function getToken(): Promise<string> {
const credential = new DefaultAzureCredential();
const tokenResponse = await credential.getToken(
"https://ai.azure.com/.default"
);
return tokenResponse.token;
}
async function main() {
const projectEndpoint = "https://YOUR-RESOURCE-NAME.services.ai.azure.com/api/projects/YOUR_PROJECT_NAME";
const deploymentName = "DeepSeek-V3.1"; // Replace with your deployment name, not the model ID
const baseURL = projectEndpoint.replace(/\/+$/, "") + "/openai/v1";
const token = await getToken();
const client = new OpenAI({
baseURL,
apiKey: token,
});
const response = await client.responses.create({
model: deploymentName,
input: "What are the top 3 benefits of cloud computing? Be concise.",
max_output_tokens: 500,
});
console.log(`Response: ${response.output_text}`);
console.log(`Status: ${response.status}`);
console.log(`Output tokens: ${response.usage?.output_tokens}`);
}
main();
使用 Microsoft Entra ID 進行認證需要一些初步設定。 首先,安裝 Azure Identity 用戶端函式庫。 關於如何安裝此函式庫的更多選項,請參閱 Java 的 Azure Identity 用戶端函式庫。
新增 Azure Identity 客戶端函式庫:
<dependencies>
<dependency>
<groupId>com.openai</groupId>
<artifactId>openai-java</artifactId>
<version>4.22.0</version>
</dependency>
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-identity</artifactId>
<version>1.15.4</version>
</dependency>
</dependencies>
設定完成後,從 Azure.identity 中選擇要使用的憑證類型。 例如,使用 來驗證客戶端。 使用 進行驗證最為簡單,因為它會在其執行環境中找到最佳的憑證。
請使用以下程式碼在 project 路徑中配置 OpenAI 用戶端物件,指定你的部署,並產生回應。
import com.azure.core.credential.TokenRequestContext;
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.responses.ResponseCreateParams;
public class Sample {
public static void main(String[] args) {
String endpoint = "https://YOUR-RESOURCE-NAME.services.ai.azure.com/api/projects/YOUR_PROJECT_NAME";
String deploymentName = "DeepSeek-V3.1"; // Replace with your deployment name, not the model ID
// Get EntraID token for keyless auth
var credential = new DefaultAzureCredentialBuilder().build();
var context = new TokenRequestContext().addScopes("https://ai.azure.com/.default");
String token = credential.getToken(context).block().getToken();
// Standard OpenAI client — no Azure wrapper
// Java SDK uses /openai/v1 path (no api-version needed; SDK manages versioning internally)
String baseUrl = endpoint.replaceAll("/+$", "") + "/openai/v1";
OpenAIClient client = OpenAIOkHttpClient.builder()
.baseUrl(baseUrl)
.apiKey(token)
.build();
var response = client.responses().create(
ResponseCreateParams.builder()
.model(deploymentName)
.input("What are the top 3 benefits of cloud computing? Be concise.")
.maxOutputTokens(500)
.build()
);
System.out.printf("Response: %s%n", getOutputText(response));
System.out.printf("Status: %s%n", response.status());
response.usage().ifPresent(u ->
System.out.printf("Output tokens: %d%n", u.outputTokens()));
}
}
package main
import (
"context"
"fmt"
"os"
"strings"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/openai/openai-go/v3"
"github.com/openai/openai-go/v3/option"
"github.com/openai/openai-go/v3/responses"
)
func main() {
projectEndpoint := "https://YOUR-RESOURCE-NAME.services.ai.azure.com/api/projects/YOUR_PROJECT_NAME"
deploymentName := "DeepSeek-V3.1" // Replace with your deployment name, not the model ID
ctx := context.Background()
// Get EntraID token for keyless auth
credential, err := azidentity.NewDefaultAzureCredential(nil)
token, err := credential.GetToken(ctx, policy.TokenRequestOptions{
Scopes: []string{"https://ai.azure.com/.default"},
})
// Standard OpenAI client — no Azure wrapper (no api-version needed with /v1 path)
baseURL := strings.TrimRight(projectEndpoint, "/") + "/openai/v1"
client := openai.NewClient(
option.WithBaseURL(baseURL),
option.WithAPIKey(token.Token),
)
resp, err := client.Responses.New(ctx, responses.ResponseNewParams{
Model: deploymentName,
Input: responses.ResponseNewParamsInputUnion{
OfString: openai.String("What are the top 3 benefits of cloud computing? Be concise."),
},
MaxOutputTokens: openai.Int(500),
})
fmt.Printf("Response: %s\n", resp.OutputText())
fmt.Printf("Status: %s\n", resp.Status)
fmt.Printf("Output tokens: %d\n", resp.Usage.OutputTokens)
}
回應包含產生的文字以及模型和使用中繼資料。
支援的 Foundry 模型
支援部分 Foundry 模型以配合回應 API 使用。
在 Foundry 入口網站查看支援的模型
欲在 Foundry 入口網站查看完整支援型號清單:
- 登入 Microsoft Foundry。 確定 新鑄造廠 的開關是開啟的。 這些步驟指的是 Foundry(新)。
- 在右上角的導覽中選擇 「發現 」,然後在左側窗格選擇 「型號 」。
- 打開 「能力 」下拉選單,選擇代理 支援 的篩選器。
支援型號列表
本節列出部分支援與回應 API 使用的 Foundry 模型。 關於Azure支援的 OpenAI 模型,請參見 Available Azure OpenAI 模型。
由 Azure 直接銷售的型號:
- MAI-DS-R1:確定性、精確度導向的推理。
- GROK-4:用於複雜多步驟問題解決的前沿尺度推理。
- grok-4-fast-reasoning::針對工作流程自動化最佳化的加速推理。
- grok-4-fast-non-reasoning:高輸送量、低延遲的生成與系統路由。
- GROK-3:針對複雜系統層級的工作流程提供強而有力的推理。
- Grok-3-mini:輕量化模型,優化於互動式、大量使用情境。
- Llama-3.3-70B-Instruct:企業問答、決策支援及系統協調的多功能模型。
- Llama-4-Maverick-17B-128E-Instruct-FP8:FP8 優化模型,提供快速且具成本效益的推理。
- DeepSeek-V3-0324:跨文本與影像的多模態理解。
- DeepSeek-V3.1:強化多模態推理與接地檢索。
- DeepSeek-R1-0528:進階長式與多步驟推理。
- GPT-OSS-120b:支持透明度與可重現性的開放生態系統模型。
解決常見錯誤
| 錯誤 |
原因 |
解決辦法 |
| 401 未經授權 |
憑證無效或過期 |
請確認您的 已在資源上指派 Cognitive Services OpenAI User 角色。 |
| 404 找不到 |
錯誤的端點或部署名稱 |
確認你的端點網址包含 且部署名稱是否符合你的 Foundry 入口網站。 |
| 400 型號不支援 |
模型不支援回應 API |
請檢查 支援的模型清單 ,並確認你的部署使用的是相容的型號。 |
相關內容