Microsoft Agent Framework では、3 種類の異なる Azure OpenAI クライアントがサポートされています。各クライアントは、異なるツール機能を備えた異なる API サーフェスを対象としています。
| クライアントの種類 | API | 最適な対象者 |
|---|---|---|
| チャットの完了 | Chat Completions API | 単純なエージェント、広範なモデルのサポート |
| 応答 | 応答API | ホストされたツール (コード インタープリター、ファイル検索、Web 検索、ホストされた MCP) を使用したフル機能のエージェント |
| アシスタント | Assistants API | コード インタープリターとファイル検索を使用するサーバーマネージド エージェント |
ヒント
OpenAI の直接の相当品 (OpenAIChatClient、OpenAIResponsesClient、OpenAIAssistantsClient) については、OpenAI プロバイダーのページを参照してください。 ツールのサポートは同じです。
はじめに
必要な NuGet パッケージをプロジェクトに追加します。
dotnet add package Azure.AI.OpenAI --prerelease
dotnet add package Azure.Identity
dotnet add package Microsoft.Agents.AI.OpenAI --prerelease
すべての Azure OpenAI クライアントの種類は、最初に AzureOpenAIClientを作成します。
using System;
using Azure.AI.OpenAI;
using Azure.Identity;
using Microsoft.Agents.AI;
AzureOpenAIClient client = new AzureOpenAIClient(
new Uri("https://<myresource>.openai.azure.com"),
new DefaultAzureCredential());
Warnung
DefaultAzureCredential は開発には便利ですが、運用環境では慎重に考慮する必要があります。 運用環境では、待機時間の問題、意図しない資格情報のプローブ、フォールバック メカニズムによる潜在的なセキュリティ リスクを回避するために、特定の資格情報 ( ManagedIdentityCredential など) を使用することを検討してください。
チャット完了クライアント
Chat Completion クライアントでは、ChatCompletion API を使用してエージェントを簡単に作成できます。
var chatClient = client.GetChatClient("gpt-4o-mini");
AIAgent agent = chatClient.AsAIAgent(
instructions: "You are good at telling jokes.",
name: "Joker");
Console.WriteLine(await agent.RunAsync("Tell me a joke about a pirate."));
サポートされているツール: 関数ツール、Web 検索、ローカル MCP ツール。
応答クライアント
Responses クライアントは、コード インタープリター、ファイル検索、Web 検索、ホストされた MCP など、最も豊富なツールサポートを提供します。
var responsesClient = client.GetResponseClient("gpt-4o-mini");
AIAgent agent = responsesClient.AsAIAgent(
instructions: "You are a helpful coding assistant.",
name: "CodeHelper");
Console.WriteLine(await agent.RunAsync("Write a Python function to sort a list."));
サポートされているツール: 関数ツール、ツール承認、コード インタープリター、ファイル検索、Web 検索、ホストされた MCP、ローカル MCP ツール。
クライアントのアシスタント
Assistants クライアントは、組み込みのコード インタープリターとファイル検索を使用して、サーバー管理エージェントを作成します。
var assistantsClient = client.GetAssistantClient();
AIAgent agent = assistantsClient.AsAIAgent(
instructions: "You are a data analysis assistant.",
name: "DataHelper");
Console.WriteLine(await agent.RunAsync("Analyze trends in the uploaded data."));
サポートされているツール: 関数ツール、コード インタープリター、ファイル検索、ローカル MCP ツール。
関数ツール
カスタム関数ツールは、任意の Azure OpenAI エージェントに提供できます。
using System.ComponentModel;
using Microsoft.Extensions.AI;
[Description("Get the weather for a given location.")]
static string GetWeather([Description("The location to get the weather for.")] string location)
=> $"The weather in {location} is cloudy with a high of 15°C.";
AIAgent agent = new AzureOpenAIClient(
new Uri(endpoint),
new DefaultAzureCredential())
.GetChatClient(deploymentName)
.AsAIAgent(instructions: "You are a helpful assistant", tools: [AIFunctionFactory.Create(GetWeather)]);
Console.WriteLine(await agent.RunAsync("What is the weather like in Amsterdam?"));
ストリーミング応答
await foreach (var update in agent.RunStreamingAsync("Tell me a joke about a pirate."))
{
Console.Write(update);
}
ヒント
実行可能な完全な例については、 .NET サンプル を参照してください。
エージェントの使用
3 つのクライアントの種類はすべて、同じエージェント操作 (ストリーミング、スレッド、ミドルウェア) をサポートする標準の AIAgent を生成します。
詳細については、 作業の開始に関するチュートリアルを参照してください。
Installation
pip install agent-framework --pre
コンフィギュレーション
クライアントの種類ごとに異なる環境変数が使用されます。
チャットの完了
AZURE_OPENAI_ENDPOINT="https://<myresource>.openai.azure.com"
AZURE_OPENAI_CHAT_DEPLOYMENT_NAME="gpt-4o-mini"
Responses
AZURE_OPENAI_ENDPOINT="https://<myresource>.openai.azure.com"
AZURE_OPENAI_RESPONSES_DEPLOYMENT_NAME="gpt-4o-mini"
Assistants
AZURE_OPENAI_ENDPOINT="https://<myresource>.openai.azure.com"
AZURE_OPENAI_CHAT_DEPLOYMENT_NAME="gpt-4o-mini"
必要に応じて、次の設定も可能です。
AZURE_OPENAI_API_VERSION="2024-10-21" # Default API version
AZURE_OPENAI_API_KEY="<your-api-key>" # If not using Azure CLI authentication
すべてのクライアントは、認証に Azure 資格情報を使用します。 最も簡単な方法は、AzureCliCredentialを実行した後にaz loginすることです。
チャット完了クライアント
AzureOpenAIChatClient では、チャット補完 API が使用されます。これは、広範なモデルをサポートする最も簡単なオプションです。
import asyncio
from agent_framework.azure import AzureOpenAIChatClient
from azure.identity import AzureCliCredential
async def main():
agent = AzureOpenAIChatClient(credential=AzureCliCredential()).as_agent(
name="Joker",
instructions="You are good at telling jokes.",
)
result = await agent.run("Tell me a joke about a pirate.")
print(result)
asyncio.run(main())
サポートされているツール: 関数ツール、Web 検索、ローカル MCP ツール。
応答クライアント
AzureOpenAIResponsesClient では、ホストされているツールで最も機能豊富なオプションである Responses API が使用されます。
import asyncio
from agent_framework.azure import AzureOpenAIResponsesClient
from azure.identity import AzureCliCredential
async def main():
agent = AzureOpenAIResponsesClient(credential=AzureCliCredential()).as_agent(
name="FullFeaturedAgent",
instructions="You are a helpful assistant with access to many tools.",
)
result = await agent.run("Write and run a Python script that calculates fibonacci numbers.")
print(result)
asyncio.run(main())
Azure AI Foundry プロジェクトのエンドポイント用応答クライアント
AzureOpenAIResponsesClient は、Azure AI Foundry プロジェクト エンドポイントから作成することもできます。
from agent_framework.azure import AzureOpenAIResponsesClient
from azure.identity import AzureCliCredential
client = AzureOpenAIResponsesClient(
project_endpoint="https://<your-project>.services.ai.azure.com/api/projects/<project-id>",
deployment_name="gpt-4o-mini",
credential=AzureCliCredential(),
)
agent = client.as_agent(
name="FoundryResponsesAgent",
instructions="You are a helpful assistant.",
)
サポートされているツール: 関数ツール、ツール承認、コード インタープリター、ファイル検索、Web 検索、ホストされた MCP、ローカル MCP ツール。
応答クライアントを備えたホスト型ツール
Responses クライアントは、ホストされているツールの種類ごとに get_*_tool() メソッドを提供します。
async def hosted_tools_example():
client = AzureOpenAIResponsesClient(credential=AzureCliCredential())
code_interpreter = client.get_code_interpreter_tool()
web_search = client.get_web_search_tool()
file_search = client.get_file_search_tool(vector_store_ids=["vs_abc123"])
mcp_tool = client.get_mcp_tool(
name="GitHub",
url="https://api.githubcopilot.com/mcp/",
approval_mode="never_require",
)
agent = client.as_agent(
name="PowerAgent",
instructions="You have access to code execution, web search, files, and GitHub.",
tools=[code_interpreter, web_search, file_search, mcp_tool],
)
result = await agent.run("Search the web for Python best practices, then write a summary.")
print(result)
クライアントのアシスタント
AzureOpenAIAssistantsClient では、Assistants API (組み込みのコード インタープリターとファイル検索を使用するサーバーマネージド エージェント) が使用されます。
async with コンテキスト マネージャーを使用して、アシスタントのライフサイクルを自動管理します。
import asyncio
from agent_framework.azure import AzureOpenAIAssistantsClient
from azure.identity import AzureCliCredential
async def main():
async with AzureOpenAIAssistantsClient(credential=AzureCliCredential()).as_agent(
name="DataAnalyst",
instructions="You analyze data using code execution.",
) as agent:
result = await agent.run("Calculate the first 20 prime numbers.")
print(result)
asyncio.run(main())
サポートされているツール: 関数ツール、コード インタープリター、ファイル検索、ローカル MCP ツール。
一般的な機能
3 つのクライアントの種類はすべて、次の標準エージェント機能をサポートしています。
関数ツール
from agent_framework import tool
@tool
def get_weather(location: str) -> str:
"""Get the weather for a given location."""
return f"The weather in {location} is sunny, 25°C."
async def example():
agent = AzureOpenAIResponsesClient(credential=AzureCliCredential()).as_agent(
instructions="You are a weather assistant.",
tools=get_weather,
)
result = await agent.run("What's the weather in Tokyo?")
print(result)
複数ターンの会話
async def thread_example():
agent = AzureOpenAIResponsesClient(credential=AzureCliCredential()).as_agent(
instructions="You are a helpful assistant.",
)
session = await agent.create_session()
result1 = await agent.run("My name is Alice", session=session)
print(result1)
result2 = await agent.run("What's my name?", session=session)
print(result2) # Remembers "Alice"
ストリーミング
async def streaming_example():
agent = AzureOpenAIResponsesClient(credential=AzureCliCredential()).as_agent(
instructions="You are a creative storyteller.",
)
print("Agent: ", end="", flush=True)
async for chunk in agent.run("Tell me a short story about AI.", stream=True):
if chunk.text:
print(chunk.text, end="", flush=True)
print()
エージェントの使用
すべてのクライアントの種類では、同じ操作をサポートする標準の Agent が生成されます。
詳細については、 作業の開始に関するチュートリアルを参照してください。