OpenAI Agent SDKでアプリを構築する

目次

まえがき

OpenAIから開発者向けにAgent SDKが発表されたました。これを機にpythonとReactでゼロからアプリ構築をしていきたいと思います。今回は、シンプルなチャットアプリを構築していきます。

ファイル作成

フロントエンドファイルの作成

ルートディレクトリでコマンドを入力します。

npx create-react-app frontend

インストール完了後、以下のコマンドを入力してクライアントを起動します。

cd frontend
npm start

バックエンドファイルの作成

cd ..
mkdir backend
cd backend
touch main.py

main.pyファイルを作成したら以下のソースコードを貼り付けます。

from agents import Agent, Runner

agent = Agent(name="Assistant", instructions="You are a helpful assistant")

result = Runner.run_sync(agent, "Write a haiku about recursion in programming.")
print(result.final_output)

# Code within the code,
# Functions calling themselves,
# Infinite loop's dance.

次に、agent SDKをインストールしていきます。

pip install openai-agents

インストールが完了したら、OpenAIのAPIキーをターミナル上にExportします。

export OPENAI_API_KEY=your_api_key

最後に、以下のコマンドでバックエンドの実行を確認します。

python main.py

Runner Agent

Runnerクラスでエージェントの実行を行います。

from agents import Agent, Runner

async def main():
    agent = Agent(name="Assistant", instructions="You are a helpful assistant")

    result = await Runner.run(agent, "Write a haiku about recursion in programming.")
    print(result.final_output)
    # Code within the code,
    # Functions calling themselves,
    # Infinite loop's dance.

ストリーミング出力を行っている場合は、 RunResultStreamingがエージェントの実行結果に含まれています。

以下のコードが呼び出し方法の参考になります。

import asyncio
from openai.types.responses import ResponseTextDeltaEvent
from agents import Agent, Runner

async def main():
    agent = Agent(
        name="Joker",
        instructions="You are a helpful assistant.",
    )

    result = Runner.run_streamed(agent, input="Please tell me 5 jokes.")
    async for event in result.stream_events():
        if event.type == "raw_response_event" and isinstance(event.data, ResponseTextDeltaEvent):
            print(event.data.delta, end="", flush=True)


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

Response API (Web Search Tool)

ResponseAPIを使って検索機能を実装します。

import openai from OpenAI

client = OpenAI (
    api_key = "XXXXXX"
)

response = client.response.create(
    model="gpt-4o",
    tools=[{"type": "web_search_preview"}],
    input="2025年3月14日の政治の事件は?",
)
#APIの結果全てを取得する場合
print(response)
#テキストのみ取得する場合
print(response.output_text)
Response(id='XXXXXXXXXXX', created_at=1742000929.0, error=None, incomplete_details=None, instructions=None, metadata={}, model='gpt-4o-2024-08-06', object='response', output=[ResponseFunctionWebSearch(id='ws_67d4d32239fc8192b80a8ff92c37cdd0027548a8deef9e5f', status='completed', type='web_search_call'), ResponseOutputMessage(id='YYYYYYYYYYYYYYY', content=[ResponseOutputText(annotations=[AnnotationURLCitation(end_index=192, start_index=102, title='シリア暫定憲法を承認\u3000正式な政権移行に5年\u3000表現の自由や女性の権利も盛り込まれる (2025年3月14日掲載) - ライブドアニュース', type='url_citation', url='https://news.livedoor.com/topics/detail/28341151/?utm_source=openai'), AnnotationURLCitation(end_index=331, start_index=251, title='2025年3月14日のヘッドラインニュース - GIGAZINE', type='url_citation', url='https://gigazine.net/news/20250314-headline/?utm_source=openai'), AnnotationURLCitation(end_index=522, start_index=432, title='トランプ政権、「出生地主義」制限で最高裁に申し立て (2025年3月14日掲載) - ライブドアニュース', type='url_citation', url='https://news.livedoor.com/topics/detail/28341057/?utm_source=openai'), AnnotationURLCitation(end_index=715, start_index=625, title='北朝鮮が自民党の改憲推進に警告\u3000韓米日安保協力を非難 (2025年3月14日掲載) - ライブドアニュース', type='url_citation', url='https://news.livedoor.com/topics/detail/28341246/?utm_source=openai'), AnnotationURLCitation(end_index=899, start_index=788, title='石破首相、改めて「違法性はない」~商品券配布問題(2025年3月14日掲載)|日テレNEWS NNN', type='url_citation', url='https://news.ntv.co.jp/category/politics/08c6b04760d444e88c165308d4952c5b?utm_source=openai')], text='2025年3月14日には、以下の政治的な出来事が報じられました。\n\n**シリアの暫定憲法承認**\n\nシリアのシャラア暫定大統領は、正式な政権への移行期間を5年と定める暫定憲法草案に署名し、承認しました。 ([news.livedoor.com](https://news.livedoor.com/topics/detail/28341151/?utm_source=openai))\n\n**日本の政治家襲撃事件**\n\nNHK党の立花孝志党首が、財務省前でナタを持った男に襲われる事件が発生しました。 ([gigazine.net](https://gigazine.net/news/20250314-headline/?utm_source=openai))\n\n**米国の出生地主義制限に関する最高裁への申し立て**\n\nトランプ米政権は、米国で生まれればほぼ無条件で米国籍を得られる「出生地主義」を大幅に制限する大統領令を認めるよう、最高裁に申し立てました。 ([news.livedoor.com](https://news.livedoor.com/topics/detail/28341057/?utm_source=openai))\n\n**北朝鮮による日本の改憲推進への警告**\n\n北朝鮮の朝鮮中央通信は、日本の自民党が戦力保有と交戦権を認めない「平和憲法」の改正を推進しようとしていることを指摘し、韓米日の安全保障協力を非難しました。 ([news.livedoor.com](https://news.livedoor.com/topics/detail/28341246/?utm_source=openai))\n\n**石破首相の商品券配布問題**\n\n石破首相が自民党新人議員に10万円相当の商品券を配っていた問題で、首相は「違法性はない」と強調しました。 ([news.ntv.co.jp](https://news.ntv.co.jp/category/politics/08c6b04760d444e88c165308d4952c5b?utm_source=openai))\n\nこれらの出来事が、2025年3月14日に報じられた主な政治的なニュースです。 ', type='output_text')], role='assistant', status='completed', type='message')], parallel_tool_calls=True, temperature=1.0, tool_choice='auto', tools=[WebSearchTool(type='web_search_preview', search_context_size='medium', user_location=UserLocation(type='approximate', city=None, country='US', region=None, timezone=None))], top_p=1.0, max_output_tokens=None, previous_response_id=None, reasoning=Reasoning(effort=None, generate_summary=None), status='completed', text=ResponseTextConfig(format=ResponseFormatText(type='text')), truncation='disabled', usage=ResponseUsage(input_tokens=331, output_tokens=536, output_tokens_details=OutputTokensDetails(reasoning_tokens=0), total_tokens=867, input_tokens_details={'cached_tokens': 0}), user=None, store=True
よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!
目次