0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Foundry Prompt Agent から APIM 経由でモデル呼出(閉域環境)

0
Last updated at Posted at 2026-11-03

本記事記述および実装内容は、多くの部分をAIで処理しており、人間チェックは甘いです

Foundry の Prompt Agent から API Management (APIM) 経由で Foundry のモデルを呼ぶ構成 (BYOM) を、Private Network だけで通すための手順を記録しました。APIM の受信は Private Endpoint のみ (publicNetworkAccess = Disabled) にして、エージェントからのモデル呼び出しが成功することを確認しています。

前提条件

  • Azure CLI、Bicep、git、uv (Python 3.10 以上) が使える
  • Foundry、APIM、VNet、Private Endpoint を作成できる権限
  • プロジェクトのマネージド ID を az ad sp show で引ける Entra の権限
  • リージョンはプロジェクト側 Japan East、モデル側 East US 2 (モデルのクォータは別途確認)

Steps

1. サンプルをデプロイ

foundry-samples の 16-private-network-standard-agent-apim-setup/extensions/byom-cross-region を使います。デプロイすると次が揃います。

構成要素 内容
VNet とサブネット agent-subnet (Microsoft.App/environments に委任)、pe-subnet、backend-pe、apim-outbound (Microsoft.Web/serverFarms に委任、NSG あり)
Foundry (プロジェクト側) BYO VNet のネットワークインジェクション、キャパビリティホストあり
APIM Standard v2、送信 VNet 統合 (apim-outbound)、/inference API
Foundry (モデル側) publicNetworkAccess = Disabled、Private Endpoint
/inference API のポリシー プロジェクトのマネージド ID のトークンを検証し、APIM のマネージド ID でバックエンドを呼ぶ
BYOM 接続 ApiManagement カテゴリ、認証はプロジェクトのマネージド ID

samples/parameters-cross-region.json は、自分の環境に合わせて書き換えます。検証では次のようにしました。

パラメーター 検証での値
location (プロジェクト側) japaneast (サンプルは canadaeast)
backendLocation (モデル側) eastus2 (サンプルは japaneast)
apimName、backendAccountName 一意な名前
backendModelDeployments gpt-5-mini (2025-08-07) の 1 件、capacity 10

プロジェクトのマネージド ID は作成後にしか分からないので、2 回に分けてデプロイします (README の Pass 1 / Pass 2)。同じ deploymentTimestamp とリソース名で実行してください。

cd foundry-samples/infrastructure/infrastructure-setup-bicep/16-private-network-standard-agent-apim-setup/extensions/byom-cross-region

az group create --name <rg> --location japaneast

# Pass 1: プロジェクトのマネージド ID を作る
az deployment group create \
  --resource-group <rg> \
  --template-file main.bicep \
  --parameters @samples/parameters-cross-region.json \
  --parameters deploymentTimestamp=<fixed-timestamp> \
  --parameters projectMiClientId=00000000-0000-0000-0000-000000000000 \
  --parameters developerIpCidr=<your-global-ip>/32
# Pass 2: マネージド ID の appId (client ID) で APIM のポリシーを更新する
PROJECT_ID="<Pass 1 の outputs.projectId>"
PROJECT_PRINCIPAL_ID=$(az resource show --ids "$PROJECT_ID" \
  --api-version 2025-04-01-preview --query identity.principalId -o tsv)
PROJECT_MI_CLIENT_ID=$(az ad sp show --id "$PROJECT_PRINCIPAL_ID" --query appId -o tsv)

az deployment group create \
  --resource-group <rg> \
  --template-file main.bicep \
  --parameters @samples/parameters-cross-region.json \
  --parameters deploymentTimestamp=<same-fixed-timestamp> \
  --parameters projectMiClientId="$PROJECT_MI_CLIENT_ID" \
  --parameters developerIpCidr=<your-global-ip>/32

検証時 (foundry-samples の 3c0d9e3e) は、次の 3 点でつまずきました。

  • Pass 1 が NetworkSecurityGroupNotFound で失敗しました。main.bicep が apim-outbound サブネットを NSG なしで上書きしていたためです(私の環境固有の問題)。git checkout aad1d4b0 -- main.bicep で戻してから Pass 1 を実行すると通ります。
  • 自分の PC からエージェントを作るには、開発者ユーザーに Foundry User ロールが必要です (サンプルは付与しません)。反映まで約 2 分かかります。

2. APIM に受信の Private Endpoint を追加

サンプルは、新規に作る APIM には受信の Private Endpoint を作りません。pe-subnet に Private Endpoint を作り、privatelink.azure-api.net をエージェントの VNet にリンクします。

apim-inbound-pe.bicep
param location string = resourceGroup().location
param apimName string
param vnetName string
param peSubnetName string = 'pe-subnet'
param apimPeName string = 'pep-${apimName}'

resource apim 'Microsoft.ApiManagement/service@2024-05-01' existing = {
  name: apimName
}

resource vnet 'Microsoft.Network/virtualNetworks@2024-05-01' existing = {
  name: vnetName
}

resource peSubnet 'Microsoft.Network/virtualNetworks/subnets@2024-05-01' existing = {
  parent: vnet
  name: peSubnetName
}

resource dnsZone 'Microsoft.Network/privateDnsZones@2024-06-01' = {
  name: 'privatelink.azure-api.net'
  location: 'global'
}

resource dnsZoneLink 'Microsoft.Network/privateDnsZones/virtualNetworkLinks@2024-06-01' = {
  parent: dnsZone
  name: 'link-${vnetName}'
  location: 'global'
  properties: {
    registrationEnabled: false
    virtualNetwork: {
      id: vnet.id
    }
  }
}

resource pe 'Microsoft.Network/privateEndpoints@2024-05-01' = {
  name: apimPeName
  location: location
  properties: {
    subnet: {
      id: peSubnet.id
    }
    privateLinkServiceConnections: [
      {
        name: '${apimPeName}-plsc'
        properties: {
          privateLinkServiceId: apim.id
          groupIds: [
            'Gateway'
          ]
        }
      }
    ]
  }
}

resource peDnsGroup 'Microsoft.Network/privateEndpoints/privateDnsZoneGroups@2024-05-01' = {
  parent: pe
  name: 'default'
  properties: {
    privateDnsZoneConfigs: [
      {
        name: 'privatelink-azure-api-net'
        properties: {
          privateDnsZoneId: dnsZone.id
        }
      }
    ]
  }
  dependsOn: [
    dnsZoneLink
  ]
}
az deployment group create \
  --resource-group <rg> \
  --template-file apim-inbound-pe.bicep \
  --parameters apimName=<apim-name> vnetName=<vnet-name>

3. APIM の公開アクセスを無効にする

APIM_ID=$(az apim show -g <rg> -n <apim-name> --query id -o tsv)

az rest --method patch \
  --url "https://management.azure.com${APIM_ID}?api-version=2024-05-01" \
  --body '{"properties":{"publicNetworkAccess":"Disabled"}}'

# Succeeded / Disabled になるまで待つ (約 4 分)
az apim show -g <rg> -n <apim-name> --query "[provisioningState,publicNetworkAccess]"

反映後、自分の PC から APIM のゲートウェイ URL を curl すると、拒否されます。HTTP ステータスは 404 で、本文の statusCode が 403 です。

{ "statusCode": 403, "message": "Request originated from client public IP address <your-ip>, public network access on this `Microsoft.ApiManagement/service/<apim-name>` is disabled. To connect to `Microsoft.ApiManagement/service/<apim-name>`, please use the Private Endpoint from inside your virtual network. To learn more https://aka.ms/apim-privateendpoint " }

テスト

Prompt Agent を作って Responses API で呼びます。モデルは <接続名>/<デプロイ名> で指定します (サンプルの既定の接続名は ai-gateway)。

invoke_agent.py
# /// script
# requires-python = ">=3.10"
# dependencies = ["azure-ai-projects>=2.0.0,<3", "azure-identity>=1.19", "openai>=1.60"]
# ///
from azure.ai.projects import AIProjectClient
from azure.ai.projects.models import PromptAgentDefinition
from azure.identity import DefaultAzureCredential

ENDPOINT = "https://<account>.services.ai.azure.com/api/projects/<project>"
MODEL = "ai-gateway/gpt-5-mini"

project = AIProjectClient(endpoint=ENDPOINT, credential=DefaultAzureCredential(process_timeout=60))
agent = project.agents.create_version(
    agent_name="byom-verify-agent",
    definition=PromptAgentDefinition(model=MODEL, instructions="You are a helpful assistant. Answer in at most ten words."),
)

client = project.get_openai_client()
for i in range(5):
    conversation = client.conversations.create()
    response = client.responses.create(
        conversation=conversation.id,
        input="Say hello in five words.",
        extra_body={"agent_reference": {"name": agent.name, "type": "agent_reference"}},
    )
    print(i + 1, response.status, response.output_text)
uv run invoke_agent.py

APIM の公開アクセスが無効のまま、5 回とも completed で応答が返りました。公開経路は閉じているので、APIM への呼び出しは Private Endpoint 経由です。

APIM のログで送信元を確認する (任意)

APIM の診断設定 (カテゴリ GatewayLogs、送信先 Log Analytics、リソース固有テーブル) を有効にしておきます。

ApiManagementGatewayLogs
| where TimeGenerated > ago(30m)
| project TimeGenerated, ApiId, CallerIpAddress, ResponseCode, BackendResponseCode, LastErrorReason, CorrelationId
| order by TimeGenerated desc

検証では、CallerIpAddress が agent-subnet のプライベート IP で、ResponseCode と BackendResponseCode は 200 でした。APIM の /inference API の inbound の先頭に trace ポリシーを入れて context.Request.PrivateEndpointConnection を出すと、Private Endpoint 経由かどうかも確認できます。

補足

次の点は確認していません。

  • 受信 Private Endpoint や Private DNS ゾーンを 1 つずつ外した切り分け (どれが必須かの確認)
  • Private DNS ゾーンなし、カスタム DNS、マネージド VNet の構成
  • ModelGateway 接続、ホステッドエージェント
  • 自分の PC からエージェントを作るために、プロジェクト側の Foundry は developerIpCidr の IP だけ公開しています。プロジェクト側も完全に閉じる場合は、VNet 内の VM などから実行します。

また、BYOM で APIM の受信を閉域にする構成を明記した公式ドキュメントは見つけられませんでした。本番で採用する前に確認してください。

参考

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?