次の方法で共有


OpenAI エージェント

Microsoft Agent Framework では、それぞれ異なるツール機能を備えた異なる API サーフェスを対象とする、3 つの異なる OpenAI クライアントの種類がサポートされています。

クライアントの種類 API 最適な対象者
チャットの完了 Chat Completions API 単純なエージェント、広範なモデルのサポート
応答 応答API ホストされたツール (コード インタープリター、ファイル検索、Web 検索、ホストされた MCP) を使用したフル機能のエージェント
アシスタント Assistants API コード インタープリターとファイル検索を使用するサーバーマネージド エージェント

ヒント

Azure OpenAI に相当する (AzureOpenAIChatClientAzureOpenAIResponsesClientAzureOpenAIAssistantsClient) については、 Azure OpenAI プロバイダーのページを参照してください。 ツールのサポートは同じです。

はじめに

必要な NuGet パッケージをプロジェクトに追加します。

dotnet add package Microsoft.Agents.AI.OpenAI --prerelease

チャット完了クライアント

Chat Completion クライアントでは、ChatCompletion API を使用してエージェントを簡単に作成できます。

using Microsoft.Agents.AI;
using OpenAI;

OpenAIClient client = new OpenAIClient("<your_api_key>");
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 など、最も豊富なツールサポートを提供します。

using Microsoft.Agents.AI;
using OpenAI;

OpenAIClient client = new OpenAIClient("<your_api_key>");
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 クライアントは、組み込みのコード インタープリターとファイル検索を使用して、サーバー管理エージェントを作成します。

using Microsoft.Agents.AI;
using OpenAI;

OpenAIClient client = new OpenAIClient("<your_api_key>");
var assistantsClient = client.GetAssistantClient();

// Assistants are managed server-side
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 ツール。

ヒント

実行可能な完全な例については、 .NET サンプル を参照してください。

エージェントの使用

3 つのクライアントの種類はすべて、同じエージェント操作 (ストリーミング、スレッド、ミドルウェア) をサポートする標準の AIAgent を生成します。

詳細については、 作業の開始に関するチュートリアルを参照してください。

Installation

pip install agent-framework --pre

コンフィギュレーション

クライアントの種類ごとに異なる環境変数が使用されます。

チャットの完了

OPENAI_API_KEY="your-openai-api-key"
OPENAI_CHAT_MODEL_ID="gpt-4o-mini"

Responses

OPENAI_API_KEY="your-openai-api-key"
OPENAI_RESPONSES_MODEL_ID="gpt-4o-mini"

Assistants

OPENAI_API_KEY="your-openai-api-key"
OPENAI_CHAT_MODEL_ID="gpt-4o-mini"

チャット完了クライアント

OpenAIChatClient では、チャット補完 API が使用されます。これは、広範なモデルをサポートする最も簡単なオプションです。

import asyncio
from agent_framework.openai import OpenAIChatClient

async def main():
    agent = OpenAIChatClient().as_agent(
        name="HelpfulAssistant",
        instructions="You are a helpful assistant.",
    )
    result = await agent.run("Hello, how can you help me?")
    print(result)

asyncio.run(main())

サポートされているツール: 関数ツール、Web 検索、ローカル MCP ツール。

チャットの完了を含む Web 検索

async def web_search_example():
    client = OpenAIChatClient()
    web_search = client.get_web_search_tool()

    agent = client.as_agent(
        name="SearchBot",
        instructions="You can search the web for current information.",
        tools=web_search,
    )
    result = await agent.run("What are the latest developments in AI?")
    print(result)

応答クライアント

OpenAIResponsesClient では、ホストされているツールで最も機能豊富なオプションである Responses API が使用されます。

import asyncio
from agent_framework.openai import OpenAIResponsesClient

async def main():
    agent = OpenAIResponsesClient().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())

サポートされているツール: 関数ツール、ツール承認、コード インタープリター、ファイル検索、Web 検索、ホストされた MCP、ローカル MCP ツール。

応答クライアントを備えたホスト型ツール

Responses クライアントは、ホストされているツールの種類ごとに get_*_tool() メソッドを提供します。

async def hosted_tools_example():
    client = OpenAIResponsesClient()

    # Each tool is created via a client method
    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)

クライアントのアシスタント

OpenAIAssistantProvider では、Assistants API (組み込みのコード インタープリターとファイル検索を使用するサーバーマネージド エージェント) が使用されます。 プロバイダーは、アシスタントのライフサイクルを自動的に管理します。

import asyncio
from agent_framework.openai import OpenAIAssistantProvider
from openai import AsyncOpenAI

async def main():
    client = AsyncOpenAI()
    provider = OpenAIAssistantProvider(client)

    agent = await provider.create_agent(
        name="DataAnalyst",
        model="gpt-4o-mini",
        instructions="You analyze data using code execution.",
    )

    try:
        result = await agent.run("Calculate the first 20 prime numbers.")
        print(result)
    finally:
        await provider.delete_agent(agent.id)

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 = OpenAIResponsesClient().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 = OpenAIResponsesClient().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 = OpenAIResponsesClient().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 が生成されます。

詳細については、 作業の開始に関するチュートリアルを参照してください。

次のステップ