Microsoft Agent Framework 支援建立使用 Foundry Agent Service 的代理程式。 你可以建立持久的服務型代理實例,並擁有服務管理的聊天歷史。
使用者入門
將必要的 NuGet 套件新增至您的專案。
dotnet add package Azure.Identity
dotnet add package Microsoft.Agents.AI.AzureAI.Persistent --prerelease
創建鑄造廠代理人
第一步你需要建立一個客戶端來連接到代理服務。
using System;
using Azure.AI.Agents.Persistent;
using Azure.Identity;
using Microsoft.Agents.AI;
var persistentAgentsClient = new PersistentAgentsClient(
"https://<myresource>.services.ai.azure.com/api/projects/<myproject>",
new DefaultAzureCredential());
警告
DefaultAzureCredential 開發方便,但在生產過程中需謹慎考量。 在生產環境中,建議使用特定的憑證(例如 ManagedIdentityCredential),以避免延遲問題、意外的憑證探測,以及備援機制帶來的安全風險。
要使用 Agent Service,你需要在服務中建立一個 agent 資源。 這可以使用 Azure.AI.Agents.Persistent SDK 或使用 Microsoft Agent Framework 協助程式來完成。
使用持久性 SDK
建立持續性代理程式,並使用AIAgent將其擷取為PersistentAgentsClient。
// Create a persistent agent
var agentMetadata = await persistentAgentsClient.Administration.CreateAgentAsync(
model: "gpt-4o-mini",
name: "Joker",
instructions: "You are good at telling jokes.");
// Retrieve the agent that was just created as an AIAgent using its ID
AIAgent agent1 = await persistentAgentsClient.GetAIAgentAsync(agentMetadata.Value.Id);
// Invoke the agent and output the text result.
Console.WriteLine(await agent1.RunAsync("Tell me a joke about a pirate."));
使用 Agent Framework 輔助工具
您也可以在一個步驟中建立和傳回一個 AIAgent。
AIAgent agent2 = await persistentAgentsClient.CreateAIAgentAsync(
model: "gpt-4o-mini",
name: "Joker",
instructions: "You are good at telling jokes.");
重複使用鑄造代理程式
你可以使用它們的 ID 來取得並重用現有的 Foundry Agents。
AIAgent agent3 = await persistentAgentsClient.GetAIAgentAsync("<agent-id>");
小提示
完整可執行範例請參閱 .NET 範例 。
使用代理程式
代理程式是標準 AIAgent ,支援所有標準 AIAgent 作業。
想了解更多如何執行及與代理互動的資訊,請參閱代理 入門教學。
Configuration
環境變數
在使用 Foundry 代理之前,你需要先設定以下環境變數:
export AZURE_AI_PROJECT_ENDPOINT="https://<your-project>.services.ai.azure.com/api/projects/<project-id>"
export AZURE_AI_MODEL_DEPLOYMENT_NAME="gpt-4o-mini"
或者,您可以直接在程式碼中提供這些值。
Installation
將代理程式架構 Azure AI 套件新增至您的專案:
pip install agent-framework-azure-ai --pre
使用者入門
驗證
Foundry 代理使用 Azure 憑證來進行認證。 最簡單的方法是先執行AzureCliCredential,然後再使用az login。 所有 Azure AI 用戶端都接受 credential 統一參數,支援 TokenCredential、 AsyncTokenCredential或可呼叫的令牌提供者——令牌快取與刷新皆自動處理。
from azure.identity.aio import AzureCliCredential
async with AzureCliCredential() as credential:
# Use credential with Azure AI agent client
創建鑄造廠代理人
基本代理程式創建
建立代理程式的最簡單方法是使用 AzureAIAgentClient 並搭配環境變數:
import asyncio
from agent_framework.azure import AzureAIAgentClient
from azure.identity.aio import AzureCliCredential
async def main():
async with (
AzureCliCredential() as credential,
AzureAIAgentClient(credential=credential).as_agent(
name="HelperAgent",
instructions="You are a helpful assistant."
) as agent,
):
result = await agent.run("Hello!")
print(result.text)
asyncio.run(main())
顯式配置
您也可以明確提供設定,而不是使用環境變數:
import asyncio
from agent_framework.azure import AzureAIAgentClient
from azure.identity.aio import AzureCliCredential
async def main():
async with (
AzureCliCredential() as credential,
AzureAIAgentClient(
project_endpoint="https://<your-project>.services.ai.azure.com/api/projects/<project-id>",
model_deployment_name="gpt-4o-mini",
credential=credential,
agent_name="HelperAgent"
).as_agent(
instructions="You are a helpful assistant."
) as agent,
):
result = await agent.run("Hello!")
print(result.text)
asyncio.run(main())
使用現有的代工廠代理
使用現有代理人
如果您在 Foundry 中已有代理,可以透過提供其 ID 來使用該代理:
import asyncio
from agent_framework import Agent
from agent_framework.azure import AzureAIAgentClient
from azure.identity.aio import AzureCliCredential
async def main():
async with (
AzureCliCredential() as credential,
Agent(
chat_client=AzureAIAgentClient(
credential=credential,
agent_id="<existing-agent-id>"
),
instructions="You are a helpful assistant."
) as agent,
):
result = await agent.run("Hello!")
print(result.text)
asyncio.run(main())
建立與管理持久代理
若要進一步控制代理程式生命週期,您可以使用 Azure AI 專案用戶端建立持續性代理程式:
import asyncio
import os
from agent_framework import Agent
from agent_framework.azure import AzureAIAgentClient
from azure.ai.projects.aio import AIProjectClient
from azure.identity.aio import AzureCliCredential
async def main():
async with (
AzureCliCredential() as credential,
AIProjectClient(
endpoint=os.environ["AZURE_AI_PROJECT_ENDPOINT"],
credential=credential
) as project_client,
):
# Create a persistent agent
created_agent = await project_client.agents.create_agent(
model=os.environ["AZURE_AI_MODEL_DEPLOYMENT_NAME"],
name="PersistentAgent",
instructions="You are a helpful assistant."
)
try:
# Use the agent
async with Agent(
chat_client=AzureAIAgentClient(
project_client=project_client,
agent_id=created_agent.id
),
instructions="You are a helpful assistant."
) as agent:
result = await agent.run("Hello!")
print(result.text)
finally:
# Clean up the agent
await project_client.agents.delete_agent(created_agent.id)
asyncio.run(main())
代理功能
推理與內容過濾選項
透過 Azure AI 專案提供者建立代理時,你可以設定 default_options 啟用模型推理與負責任 AI 內容過濾。
reasoning用於具推理能力的模型:
from agent_framework.azure import AzureAIProjectAgentProvider
from azure.ai.projects.models import Reasoning
from azure.identity.aio import AzureCliCredential
async with (
AzureCliCredential() as credential,
AzureAIProjectAgentProvider(credential=credential) as provider,
):
agent = await provider.create_agent(
async with (
AzureCliCredential() as credential,
AzureAIProjectAgentProvider(credential=credential) as provider,
):
agent = await provider.create_agent(
使用 rai_config 以套用已設定的 RAI 原則:
from azure.ai.projects.models import RaiConfig
from azure.identity.aio import AzureCliCredential
async def main() -> None:
print("=== Azure AI Agent with Content Filtering ===\n")
# Replace with your RAI policy from Azure AI Foundry portal
rai_policy_name = (
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroup}/providers/"
"Microsoft.CognitiveServices/accounts/{accountName}/raiPolicies/{policyName}"
)
async with (
AzureCliCredential() as credential,
AzureAIProjectAgentProvider(credential=credential) as provider,
):
# Create agent with content filtering enabled via default_options
agent = await provider.create_agent(
功能工具
你可以為 Foundry 代理提供自訂功能工具:
import asyncio
from typing import Annotated
from agent_framework.azure import AzureAIAgentClient
from azure.identity.aio import AzureCliCredential
from pydantic import Field
def get_weather(
location: Annotated[str, Field(description="The location to get the weather for.")],
) -> str:
"""Get the weather for a given location."""
return f"The weather in {location} is sunny with a high of 25°C."
async def main():
async with (
AzureCliCredential() as credential,
AzureAIAgentClient(credential=credential).as_agent(
name="WeatherAgent",
instructions="You are a helpful weather assistant.",
tools=get_weather
) as agent,
):
result = await agent.run("What's the weather like in Seattle?")
print(result.text)
asyncio.run(main())
程式碼解譯器
Foundry 代理程式支援透過託管的程式碼直譯器執行程式碼:
import asyncio
from agent_framework.azure import AzureAIAgentClient
from azure.identity.aio import AzureCliCredential
async def main():
async with (
AzureCliCredential() as credential,
AzureAIAgentClient(credential=credential) as client,
client.as_agent(
name="CodingAgent",
instructions="You are a helpful assistant that can write and execute Python code.",
tools=client.get_code_interpreter_tool(),
) as agent,
):
result = await agent.run("Calculate the factorial of 20 using Python code.")
print(result.text)
asyncio.run(main())
串流回應
取得使用串流產生的回應:
import asyncio
from agent_framework.azure import AzureAIAgentClient
from azure.identity.aio import AzureCliCredential
async def main():
async with (
AzureCliCredential() as credential,
AzureAIAgentClient(credential=credential).as_agent(
name="StreamingAgent",
instructions="You are a helpful assistant."
) as agent,
):
print("Agent: ", end="", flush=True)
async for chunk in agent.run("Tell me a short story", stream=True):
if chunk.text:
print(chunk.text, end="", flush=True)
print()
asyncio.run(main())
使用代理程式
代理程式是標準 BaseAgent ,支援所有標準代理程式作業。
想了解更多如何執行及與代理互動的資訊,請參閱代理 入門教學。