Microsoft Foundry の Agent からLLMを呼び出すときにAPI ManagementをAI GatewayとしてToken制御をしてみました。以下の内容です。
上記リンクにある絵の一番上のAzure OpenAIリソースに対する制御をしています。

シンプルに試したかったので、モデルは動的検出ではなく、静的検出にします。静的検出と動的検出の違いはLearnの「探索方法」や「Azure API Management Setup Guide for Foundry Agents」の「Step 3: 🔍 Configure Model Discovery」に記載。
「apim-and-modelgateway-integration-guide.md」の「2️⃣ Runtime Communication Flow」にある以下の図が直観的に静的検出(Static Models)がわかります。
参考リンク
この辺を参照しながら設定しました。
Steps
1. APIMリソース作成
Azure PortalでStandard V2のAPIMリソース作成します。
作成時にシステム割当マネージドIDをON。
「⚠️ Current Limitations」に以下の記載がある通り、Standard v2かPremiumのみが2025年12月時点で対象です。
Only Azure API Management Standard v2 and Premium tiers supported
2. Azure OpenAI API をインポート
以下に従ってAPIMでAzure OpenAI API をインポート(以下のリンク参照)。
メニュー APIs -> API で 「+ Add API」をクリックして、Azure AI Foundryを選択

次画面で、対象のFoundryリソースを選択後、Configure APIで以下のように入力。Display nameとBase PathはFoundry リソース名にしておきます。

モデルをデプロイ済のgpt-5-miniに設定して、テスト実行し、問題ないことを確認。

3. コネクション定義のための情報収集
コネクション定義のためのJSONに入れる情報を収集していきます。
3.1. Target URL
API Management の API Test で Chat Completion の「Request URL」でhttps://<apim resource>.azure-api.net/<foundry resource>/openai/v1/chat/completions?api-version=v1からchat/completions?を除去してhttps://<foundry resource>.azure-api.net/ai-foundry-acl-ncus/openai/v1/部分をメモしておきます。
3.2. Inference API Version
Inference API Versionは、今回はv1を使います。
3.3. Deployment in Path
Deploy名をURLに含んでいないのでfalse
4. Connection 登録
Step 2️⃣: Create Your Gateway Connection に従ってConnectionを登録します。
GitHub上のサンプルを使い、以下のフォルダ構成にします。
├── connection-apim.bicep
├── modules
│ └── apim-connection-common.bicep
├── samples
└── parameters-static-models.json
4.1. パラメータ変更
「3. コネクション定義のための情報収集」で収集したデータを中心にparameters-static-models.jsonに埋め込んでいきます。
-
projectResourceId: Foundry Project リソースのID -
apimResourceId: API Management のリソースID -
apiName: API Management で設定したAPI名 -
connectionName: 今回登録するコネクション名 -
deploymentInPath: "false"(「3.3. Deployment in Path」参照) -
inferenceAPIVersion: "v1"(「3.2. Inference API Version」参照) -
staticModels: 下記参照
"staticModels": {
"value": [
{
"name": "gpt-5-mini",
"properties": {
"model": {
"name": "gpt-5-mini",
"version": "2025-08-07",
"format": "OpenAI"
}
}
},
{
"name": "gpt-4.1-mini",
"properties": {
"model": {
"name": "gpt-4.1-mini",
"version": "2025-04-14",
"format": "OpenAI"
}
}
}
]
}
4.2. CLIでコネクション登録
以下のコマンドを実行してコネクション登録。
az deployment group create \
--resource-group <rexource group> \
--template-file connection-apim.bicep \
--parameters @samples/parameters-static-models.json
5. Agent作成
Python SDKでAgent作成します。Foundry PortalからだとConnection経由でのモデルをAgentとひもづけできません。
5.1. 前提
Ubuntu22.04でPython3.13.2で動かしています(poetry使用)。以下がpyproject.toml。
[tool.poetry.dependencies]
python = "^3.10"
azure-identity = "^1.25.1"
jupyterlab = "^4.5.0"
azure-ai-projects = {version = "^2.0.0b2", allow-prereleases = true}
openai = "^2.11.0"
python-dotenv = "^1.2.1"
環境変数定義。
AZURE_AI_PROJECT_ENDPOINT=https://<foundry resource>.services.ai.azure.com/api/projects/<project resource>
AZURE_AI_MODEL_DEPLOYMENT_NAME=<connection name>/gpt-5-mini
5.2.Agent作成スクリプト。
Agents SDK サンプルをコピーしてスクリプト作成。
az login後に以下のコードを実行。
import os
from dotenv import load_dotenv
from azure.identity import DefaultAzureCredential
from azure.ai.projects import AIProjectClient
from azure.ai.projects.models import PromptAgentDefinition
load_dotenv(override=True)
endpoint = os.environ["AZURE_AI_PROJECT_ENDPOINT"]
with (
DefaultAzureCredential() as credential,
AIProjectClient(endpoint=endpoint, credential=credential) as project_client,
):
with project_client.get_openai_client() as openai_client:
agent = project_client.agents.create_version(
agent_name="MyAgent",
definition=PromptAgentDefinition(
model=os.environ["AZURE_AI_MODEL_DEPLOYMENT_NAME"],
instructions="You are a helpful assistant that answers general questions",
),
)
print(f"Agent created (id: {agent.id}, name: {agent.name}, version: {agent.version})")
FoundryでのAgent登録された画面。
モデル名(画面左上)はエラーが出て見えませんが、YAML上では定義できているのがわかります。

PlaygroundでモデルをAgent経由で呼び出せることを確認。

6. Agent をSDKから呼び出し
「5. Agent作成」の後続として以下のPython ScriptをJupyter上で実行
with (
DefaultAzureCredential() as credential,
AIProjectClient(endpoint=endpoint, credential=credential) as project_client,
):
with project_client.get_openai_client() as openai_client:
for number in range(3):
response = openai_client.responses.create(
input=[{"role": "user", "content": f"{str(number)}から連想する話をして?"}],
extra_body={"agent": {"name": "MyAgent", "type": "agent_reference"}},
)
print("---------\n" + response.output_text)
2回目のAgent呼び出しで以下の403エラー。正しく制御できています。
PermissionDeniedError: Error code: 403 -
{'error': {'message': "Access to model is denied - Token quota is exceeded. Try again in 17 minutes and 7 seconds. Gateway response: {'statusCode': 403, 'message': 'Token quota is exceeded. Try again in 17 minutes and 7 seconds.'} Request ID: bbeca370-d5ea-4fcc-a6e6-36b72a90bd73", 'type': 'server_error', 'param': None, 'code': 'ApiSamplingErrorUnauthorized'}}
トラブルシュート
実はConnection登録時にMFAのエラーが出ていました。
{"error":{"code":"NotSpecified","message":"Resource 'conn-apim-standard-acl-ncus' was disallowed by Azure: You are receiving this error because you tried to create, update or delete Azure resources without authenticating through MFA. User accounts must be authenticated through MFA to manage your resources. To resolve this error, go to https://aka.ms/MFAforAzure."}}
実際にMFA設定はしていたので、以下のコマンドでログアウトと再ログインをすると無事に認証でき、Connection登録できました。
az logout
az login --tenant "<tenant id>" --scope "https://management.core.windows.net//.default" --claims-challenge "<?????>"

