OpenAI Agents SDK : クイックスタート

OpenAI Agents SDK が 3月12日に公開されました。クイックスタートに進みます。

OpenAI Agents SDK : クイックスタート

作成 : クラスキャット・セールスインフォメーション
作成日時 : 03/17/2025

* 本記事は openai.github.io/openai-agents-python の以下のページを独自に翻訳した上でまとめ直し、補足説明を加えています :

* サンプルコードの動作確認はしておりますが、必要な場合には適宜、追加改変しています。
* ご自由にリンクを張って頂いてかまいませんが、sales-info@classcat.com までご一報いただけると嬉しいです。

 

クラスキャット 人工知能 研究開発支援サービス ⭐️ リニューアルしました 😉

クラスキャット は人工知能に関する各種サービスを提供しています。お気軽にご相談ください :

  • 人工知能導入個別相談会(無償)実施中! [詳細]

  • 人工知能研究開発支援 [詳細]
    1. 自社特有情報を含むチャットボット構築支援
    2. 画像認識 (医療系含む) / 画像生成

  • PoC(概念実証)を失敗させないための支援 [詳細]

お問合せ : 下記までお願いします。

  • クラスキャット セールス・インフォメーション
  • sales-info@classcat.com
  • ClassCatJP

 

 

OpenAI Agents SDK : クイックスタート

プロジェクトと仮想環境の作成

これは一度だけ行う必要があります。

mkdir my_project
cd my_project
python -m venv .venv

 
仮想環境をアクティブにする

新しい端末セッションを開始するたびにこれを実行します。

source .venv/bin/activate

 
Agents SDK をインストールする

pip install openai-agents # or `uv add openai-agents`, etc

 
OpenAI API キーを設定する

持っていない場合は、これらの手順 に従って OpenAI API キーを作成してください。

export OPENAI_API_KEY=sk-...

 

最初のエージェントを作成する

エージェントは、指示 (instructions)、名前、そして (model_config のような) オプションの config で定義されます。

from agents import Agent

agent = Agent(
    name="Math Tutor",
    instructions="You provide help with math problems. Explain your reasoning at each step and include examples",
)

 

更に 2, 3 のエージェントを追加する

追加のエージェントが同じ方法で定義できます。handoff_descriptions はハンドオフ・ルーティングを決定するための追加のコンテキストを提供します。

from agents import Agent

history_tutor_agent = Agent(
    name="History Tutor",
    handoff_description="Specialist agent for historical questions",
    instructions="You provide assistance with historical queries. Explain important events and context clearly.",
)

math_tutor_agent = Agent(
    name="Math Tutor",
    handoff_description="Specialist agent for math questions",
    instructions="You provide help with math problems. Explain your reasoning at each step and include examples",
)

 

ハンドオフを定義する

各エージェントで、エージェントがタスクを進める方法を決定するためにそこから選択できる、outgoing ハンドオフ・オプションのインベントリを定義できます。

triage_agent = Agent(
    name="Triage Agent",
    instructions="You determine which agent to use based on the user's homework question",
    handoffs=[history_tutor_agent, math_tutor_agent]
)

 

エージェント・オーケストレーションを実行する

ワークフローが実行され、トリアージ (triage) エージェントが 2 つの専門 (specialist) エージェント間で正しくルーティングするかを確認しましょう。

from agents import Runner

async def main():
    result = await Runner.run(triage_agent, "What is the capital of France?")
    print(result.final_output)

 

ガードレールを追加する

カスタム・ガードレールを追加して入力や出力上で実行できます。

from agents import GuardrailFunctionOutput, Agent, Runner
from pydantic import BaseModel

class HomeworkOutput(BaseModel):
    is_homework: bool
    reasoning: str

guardrail_agent = Agent(
    name="Guardrail check",
    instructions="Check if the user is asking about homework.",
    output_type=HomeworkOutput,
)

async def homework_guardrail(ctx, agent, input_data):
    result = await Runner.run(guardrail_agent, input_data, context=ctx.context)
    final_output = result.final_output_as(HomeworkOutput)
    return GuardrailFunctionOutput(
        output_info=final_output,
        tripwire_triggered=not final_output.is_homework,
    )

 

Put it all together

すべてをまとめて、ハンドオフと入力ガードレールを使用して、ワークフロー全体を実行してみましょう。

from agents import Agent, InputGuardrail,GuardrailFunctionOutput, Runner
from pydantic import BaseModel
import asyncio

class HomeworkOutput(BaseModel):
    is_homework: bool
    reasoning: str

guardrail_agent = Agent(
    name="Guardrail check",
    instructions="Check if the user is asking about homework.",
    output_type=HomeworkOutput,
)

math_tutor_agent = Agent(
    name="Math Tutor",
    handoff_description="Specialist agent for math questions",
    instructions="You provide help with math problems. Explain your reasoning at each step and include examples",
)

history_tutor_agent = Agent(
    name="History Tutor",
    handoff_description="Specialist agent for historical questions",
    instructions="You provide assistance with historical queries. Explain important events and context clearly.",
)


async def homework_guardrail(ctx, agent, input_data):
    result = await Runner.run(guardrail_agent, input_data, context=ctx.context)
    final_output = result.final_output_as(HomeworkOutput)
    return GuardrailFunctionOutput(
        output_info=final_output,
        tripwire_triggered=not final_output.is_homework,
    )

triage_agent = Agent(
    name="Triage Agent",
    instructions="You determine which agent to use based on the user's homework question",
    handoffs=[history_tutor_agent, math_tutor_agent],
    input_guardrails=[
        InputGuardrail(guardrail_function=homework_guardrail),
    ],
)

async def main():
    result = await Runner.run(triage_agent, "who was the first president of the united states?")
    print(result.final_output)

    result = await Runner.run(triage_agent, "what is life")
    print(result.final_output)

if __name__ == "__main__":
    asyncio.run(main())

 

トレースを見る

エージェント実行中に何が起こったかをレビューするには、OpenAI ダッシュボードの Trace ビューアー に進んで、エージェント実行のトレースをご覧ください。

 

以上