OpenAI Agents SDKでAIエージェントを構築する

今回はOpenAI Agents SDKを使い、AIエージェントを構築する基礎的な部分をご紹介します。

また、Azure OpenAIのリソースをOpenAI Agents SDKで利用する方法と、MCPを利用する方法をそれぞれ記載します。

OpenAI Agents SDKとは

OpenAI Agents SDKは、簡単で軽量なパッケージとしてOpenAIから提供されるAIアプリ構築ツールです。

このSDKを利用することで、実用的なAIアプリケーションを構築できます。過去の「Swarm」の試験的プロジェクトを改良した、実用性の高いツールです。

openai.github.io

実装準備

ターミナルなどで下記コマンドを実行し、openai-agents をインストールします。

pip install openai-agents

Azure OpenAIの利用

OpenAI Agent SDKでAzure OpenAIを利用します。

環境変数の設定

次の変数を.envへ設定します。

AZURE_OPENAI_DEPLOYMENT=<deployment_name>
AZURE_OPENAI_API_KEY=<api_key>
OPENAI_API_VERSION=<api_version>
AZURE_OPENAI_ENDPOINT=https://<resource_name>.openai.azure.com/

サンプルコード

以下のコードでは、toolとAzure OpenAIを利用するエージェントを定義しています。

traceの機能を利用するには、OPENAI_API_KEYを環境変数に設定する必要があります。

次のサイトを参考にしています。
openai.github.io

import asyncio
from dotenv import load_dotenv
import os

from openai import AsyncAzureOpenAI

from agents import (
    Agent,
    Runner,
    function_tool,
    OpenAIChatCompletionsModel,
    set_default_openai_client,
)


# function_toolの定義
@function_tool
def get_weather(city: str) -> str:
    return f"The weather in {city} is sunny."


async def main():
    AZURE_OPENAI_DEPLOYMENT_NAME = os.getenv("AZURE_OPENAI_DEPLOYMENT")

    # Create OpenAI client using Azure OpenAI
    openai_client = AsyncAzureOpenAI(
        api_key=os.getenv("AZURE_OPENAI_API_KEY"),
        api_version=os.getenv("OPENAI_API_VERSION"),
        azure_endpoint=os.getenv("AZURE_OPENAI_ENDPOINT"),
        azure_deployment=AZURE_OPENAI_DEPLOYMENT_NAME
    )

    # Set the default OpenAI client for the Agents SDK
    # 記載しないとTracing client error 401:が発生
    set_default_openai_client(openai_client, use_for_tracing=False)


    # エージェントの定義
    time_agent = Agent(
        name="time agent",
        handoff_description="Specialist agent time questions",
        instructions="You provide help with JST time information.",
        #model="gpt-4o-mini"
        model=OpenAIChatCompletionsModel( 
            model=AZURE_OPENAI_DEPLOYMENT_NAME,
            openai_client=openai_client,
        )
    )

    weather_agent = Agent(
        name="weather agent",
        instructions="Specialist agent for weather information.",
        model=OpenAIChatCompletionsModel( 
            model=AZURE_OPENAI_DEPLOYMENT_NAME,
            openai_client=openai_client,
        ),
        tools=[get_weather],
    )


    # the agent can choose from to decide how to make progress on their task.
    triage_agent = Agent(
        name="Triage Agent",
        instructions="You determine which agent to use based on the user's question",
        model=OpenAIChatCompletionsModel( 
            model=AZURE_OPENAI_DEPLOYMENT_NAME,
            openai_client=openai_client,
        ),
        handoffs=[time_agent, weather_agent]
    )



    result = await Runner.run(triage_agent, "What's the weather in Tokyo?", max_turns=5)
    print(result.final_output)
    print(f"\nrun result:\n {result.raw_responses}")


# asyncioイベントループを起動
if __name__ == "__main__":
    asyncio.run(main())

回答例

以下の例では、質問に応じてtriage_agentがどのエージェントが回答するか選択していることが確認できます。

質問
"What's the weather in Tokyo?"

回答
The weather in Tokyo is sunny.

run result:
 [ModelResponse(output=[ResponseFunctionToolCall(arguments='{}', call_id='call_OLdDx1b0KUrfZWicFS5BuN73', name='transfer_to_weather_agent', type='function_call', id='__fake_id__', status=None)], usage=Usage(requests=1, input_tokens=90, output_tokens=13, total_tokens=103), referenceable_id=None), ModelResponse(output=[ResponseFunctionToolCall(arguments='{"city":"Tokyo"}', call_id='call_8Y0DUNx2OsfdWdmjvjsFYwCC', name='get_weather', type='function_call', id='__fake_id__', status=None)], usage=Usage(requests=1, input_tokens=87, output_tokens=15, total_tokens=102), referenceable_id=None), ModelResponse(output=[ResponseOutputMessage(id='__fake_id__', content=[ResponseOutputText(annotations=[], text='The weather in Tokyo is sunny.', type='output_text')], role='assistant', status='completed', type='message')], usage=Usage(requests=1, input_tokens=116, output_tokens=9, total_tokens=125), referenceable_id=None)]  
OPENAI_API_KEY is not set, skipping trace export

MCP

MCPを利用することで、エージェントの機能を容易に拡張できます。

OpenAI Agents SDKでは簡単にMCP ServerのtoolをAgentに追加することが可能です。

詳しくは次のサイトをご参照ください。
openai.github.io

サンプルコード

次のサンプルを参考に、MCPを利用するエージェントを実装します。

github.com

今回はシンプルな時間を取得・コンバートするtoolを提供するMCP Serverを利用します。

MCP Serverについては下記を参考にしてください。

github.com

実装コードは下記の通りです。

import os
import shutil
import asyncio

# OpenAI関連モジュール
from openai import AsyncAzureOpenAI

# Agents SDK関連
from agents import (
    Agent,
    Runner,
    OpenAIChatCompletionsModel,
    set_default_openai_client,
    set_tracing_disabled,
)

# MCP関連
from agents.mcp import MCPServer, MCPServerStdio


async def run(mcp_server: MCPServer):
    AZURE_OPENAI_DEPLOYMENT_NAME = os.getenv("AZURE_OPENAI_DEPLOYMENT")

    # Create OpenAI client using Azure OpenAI
    openai_client = AsyncAzureOpenAI(
        api_key=os.getenv("AZURE_OPENAI_API_KEY"),
        api_version=os.getenv("OPENAI_API_VERSION"),
        azure_endpoint=os.getenv("AZURE_OPENAI_ENDPOINT"),
        azure_deployment=AZURE_OPENAI_DEPLOYMENT_NAME
    )

    # Set the default OpenAI client for the Agents SDK
    set_default_openai_client(openai_client, use_for_tracing=False)
    # 記載しないとTracing client error 401:が発生
    set_tracing_disabled(disabled=True)


    # mcp_serverを含んだエージェントの定義
    time_agent = Agent(
        name="time agent",
        #handoff_description="Specialist agent time questions",
        instructions="You provide time information.",
        model=OpenAIChatCompletionsModel( 
            model=AZURE_OPENAI_DEPLOYMENT_NAME,
            openai_client=openai_client,
        ),
        mcp_servers=[mcp_server],
    )

    message = "What time is it in Tokyo?"
    print("\n" + "-" * 40)
    print(f"Running: {message}")
    result = await Runner.run(starting_agent=time_agent, input=message)
    print(result.final_output)
    print(f"\nrun result:\n {result.raw_responses}")


async def main():
    async with MCPServerStdio(
        cache_tools_list=True,  # Cache the tools list, for demonstration
        params={"command": "uvx", "args": ["mcp-server-time", "--local-timezone=America/New_York"]},
    ) as server:
        await run(server)


if __name__ == "__main__":
    if not shutil.which("uvx"):
        raise RuntimeError("uvx is not installed. Please install it with `pip install uvx`.")
    
    asyncio.run(main())

回答例

以下の実行結果をを見ると、get_current_timeのtoolを利用し回答していることが確認できます。

Running: What time is it in Tokyo?
The current time in Tokyo is 4:36 PM on May 19, 2025.

run result:
 [ModelResponse(output=[ResponseFunctionToolCall(arguments='{"timezone":"Asia/Tokyo"}', call_id='call_ZHTy2Q9RJqrYr7V1LkeNu6eb', name='get_current_time', type='function_call', id='__fake_id__', status=None)], usage=Usage(requests=1, input_tokens=222, output_tokens=19, total_tokens=241), response_id=None), ModelResponse(output=[ResponseOutputMessage(id='__fake_id__', content=[ResponseOutputText(annotations=[], text='The current time in Tokyo is 4:36 PM on May 19, 2025.', type='output_text')], role='assistant', status='completed', type='message')], usage=Usage(requests=1, input_tokens=305, output_tokens=22, total_tokens=327), response_id=None)]

おわりに

今回は、Azure OpenAI のリソースを OpenAI Agents SDK で利用する方法と MCP の活用例について記載しました。

OpenAI Agents SDK は非常にシンプルにエージェントを扱える点が魅力的です。

また、エージェントの回答フローを可視化できる trace 機能を利用するには、OpenAI の OPENAI_API_KEY が必要となるため、より詳細な流れや内容を確認する場合は、OpenAI のリソースも組み合わせて活用する必要がありそうです。

執筆担当者プロフィール
寺澤 駿

寺澤 駿(日本ビジネスシステムズ株式会社)

IoTやAzure Cognitive ServicesのAIを活用したデモ環境・ソリューション作成を担当。

担当記事一覧