見出し画像

OpenAIのSwarmアプリケーションのWebUI構築チュートリアル 🚀✨

はじめに 🎉

OpenAIは「Swarm」と呼ばれる軽量なマルチエージェントフレームワークをリリースしました。このフレームワークは、複数のエージェントが効率的にユーザーと対話できるアプリケーションを作成するためのもので、教育や実験的なプロジェクトとして提供されています。本チュートリアルでは、Pythonライブラリ「Panel」を使って、Swarmフレームワークに基づいたWebUIを構築する方法について詳しく説明します。このUIでは、ユーザーがSwarmのエージェントと対話できるようにします。🤖💬

Swarmの概要 🐝

Swarmフレームワークは、複数のエージェントを利用してユーザーのリクエストを効率的に処理するために設計されています。エージェントはそれぞれ特定のタスクを担当し、ユーザーのリクエストに最も適したエージェントが対応します。このフレームワークでは、エージェント間の会話を引き継ぐ「ハンドオフ」や、エージェントのワークフローを規定する「ルーティン」といった概念を利用します。🔄✨

このチュートリアルでは、次のことを行います:

  • PythonのPanelライブラリを使ってカスタマーサポート用のWebアプリを作成する。💻

  • Swarmフレームワークを使用して、複数のエージェントを定義し、それらが特定のユーザーリクエストに対応するように設定する。👥🤝

必要なライブラリのインストール 🛠️

このチュートリアルを始める前に、以下のパッケージをインストールする必要があります。

pip install panel
pip install git+https://github.com/openai/swarm.git

Panelは、インタラクティブなWebアプリケーションを簡単に作成するためのPythonライブラリです。SwarmはGitHubのリポジトリからソースコードを使用してインストールします。📝

Swarmアプリケーションの実装 🤓

1. 必要なモジュールのインポートとAPIキーの設定 🔑

最初に必要なモジュールをインポートし、OpenAIのAPIキーを設定します。

import panel as pn
from swarm import Swarm, Agent, Result
import random
import os

os.environ["OPENAI_API_KEY"] = "sk-your-key-here"  # ここにあなたのAPIキーを設定してください

2. Swarmクライアントとエージェントの定義 🤖

次に、Swarmクライアントを初期化し、エージェントを定義します。ここでは、3つのエージェントを作成します。✨

  • 📦 製品情報取得エージェント

  • 📦 注文状況取得エージェント

  • 📦 返金処理エージェント

Swarmクライアントの初期化 🌀

client = Swarm()

エージェントの機能の定義 🛠️

次に、各エージェントの機能を定義します。ここでは、製品情報の取得、注文状況の確認、返金処理をシミュレートするための簡単な関数を用意します。💡

def get_product_info(product_id):
    # シミュレートされた製品データベース
    products = {
        "1": "📱 スマートフォン iPhone 16",
        "2": "💻 ノートパソコン MacBook Pro",
        "3": "🎧 ワイヤレスイヤホン AirPods"
    }
    return products.get(product_id, "❌ 製品が見つかりません")

def get_order_status(order_id):
    # シミュレートされた注文状況
    statuses = ["🔄 処理中", "🚚 発送済み", "📦 配達済み", "❌ キャンセル済み"]
    return random.choice(statuses)

def process_refund(order_id):
    # シミュレートされた返金処理
    success = random.choice([True, False])
    return "💰 返金が正常に処理されました" if success else "❌ 返金処理に失敗しました"

エージェントの指示の定義 📜

各エージェントに対する指示を定義し、エージェントがユーザーのリクエストをどのように処理するかを決定します。例えば、トリアージエージェントはユーザーのリクエストを適切なエージェントに振り分けます。📌

context_variables = {
    'customer_name': None,
    'last_order_id': None,
}

def triage_agent_instructions(context_variables):
    return f"""
    🤖 トリアージエージェント - eコマースサポート用
    問い合わせ内容に応じて以下に振り分けます:
    - 製品情報: 製品情報エージェント
    - 注文状況: 注文状況エージェント
    - 返品/返金: 返品・返金エージェント
    顧客名: {context_variables.get('customer_name', '不明')}
    """

def product_info_agent_instructions(context_variables):
    return f"""
    🛒 製品情報エージェント - 製品の詳細を提供します。
    顧客名: {context_variables.get('customer_name', '不明')}
    """

def order_status_agent_instructions(context_variables):
    return f"""
    📦 注文状況エージェント - 注文状況を追跡します。
    顧客名: {context_variables.get('customer_name', '不明')}
    注文ID: {context_variables.get('last_order_id', '不明')}
    """

def returns_refunds_agent_instructions(context_variables):
    return f"""
    💸 返品・返金エージェント - 返金手続きを行います。
    顧客名: {context_variables.get('customer_name', '不明')}
    注文ID: {context_variables.get('last_order_id', '不明')}
    """

エージェントのハンドオフ関数の定義 🤲

エージェント間で会話を引き継ぐためのハンドオフ関数も定義します。🔄

def transfer_to_product_info(context_variables):
    return Result(agent=product_info_agent, context_variables=context_variables)

def transfer_to_order_status(context_variables):
    return Result(agent=order_status_agent, context_variables=context_variables)

def transfer_to_returns_refunds(context_variables):
    return Result(agent=returns_refunds_agent, context_variables=context_variables)

エージェントの作成 🛠️

次に、定義したルーチンとハンドオフを統合して、各エージェントを作成します。✨

triage_agent = Agent(
    name="トリアージエージェント",
    instructions=triage_agent_instructions,
    functions=[transfer_to_product_info, transfer_to_order_status, transfer_to_returns_refunds]
)

product_info_agent = Agent(
    name="製品情報エージェント",
    instructions=product_info_agent_instructions,
    functions=[get_product_info]
)

order_status_agent = Agent(
    name="注文状況エージェント",
    instructions=order_status_agent_instructions,
    functions=[get_order_status]
)

returns_refunds_agent = Agent(
    name="返品・返金エージェント",
    instructions=returns_refunds_agent_instructions,
    functions=[process_refund]
)

3. Panelを使ったWebUIの実装 💻

次に、Panelライブラリを使って、ユーザーがエージェントと対話するためのチャットインターフェースを構築します。💬

チャットインターフェースの構築 🗨️

ChatInterfaceコンポーネントを使用して、メインのチャットUIを構築します。📲

pn.extension(design="material")

chat_interface = pn.chat.ChatInterface()
chat_interface.send("カスタマーサポートシステムへようこそ!お名前を入力してください。😊")

ユーザーメッセージを処理するコールバック関数の定義 📩

ユーザーからのメッセージを処理するためのコールバック関数を定義します。この関数は、ユーザーがメッセージを送信するたびに呼び出され、適切なエージェントにタスクを委任します。📝

current_agent = triage_agent
messages = []

def process_user_message(contents: str, user: str, instance: pn.chat.ChatInterface):
    global current_agent
    global context_variables
    global messages

    if context_variables['customer_name'] is None:
        context_variables['customer_name'] = contents
        chat_interface.send(f"こんにちは、{contents}さん!ご用件をどうぞ。😊")
    else:
        messages.append({"role": "user", "content": contents})

        response = client.run(
            agent=current_agent,
            messages=messages,
            context_variables=context_variables
        )

        chat_interface.send(response.messages[-1]['content'], user=response.agent.name)

        messages = response.messages
        current_agent = response.agent
        context_variables = response.context_variables

        if "注文" in contents:
            context_variables['last_order_id'] = f"ORD-{random.randint(1000, 9999)}"

chat_interface.callback = process_user_message

このコールバック関数では以下の処理を行います:

  • 顧客の名前が既に登録されているかを確認し、登録されていない場合は名前を尋ねる。📝

  • ユーザーのメッセージをメッセージリストに追加する。📥

  • 現在のエージェントにメッセージを委任し、次のエージェントを決定する。🔄

  • エージェントからの応答をチャットインターフェースに表示する。💬

Panelアプリケーションサービスへのチャットインターフェースの追加 🚀

最後に、作成したチャットインターフェースをPanelアプリケーションに追加し、ユーザーがブラウザで利用できるようにします。🌐

chat_interface.servable()

4. アプリケーションの実行 🎮

全てのコードが準備できたら、以下のコマンドでアプリケーションを実行します。⚡️

panel serve swarm_panel.py

これで、ブラウザ上でチャットインターフェースを利用できるようになり、ユーザーはエージェントと対話できます。💻✨

まとめ 📚

このチュートリアルでは、OpenAIのSwarmフレームワークを使用して、カスタマーサポート用のWebUIをPythonのPanelライブラリで構築する方法を説明しました。複数のエージェントを活用してユーザーのリクエストに応答するシステムを構築することで、効率的でスケーラブルなチャットボットアプリケーションを実現しました。🤖✨

いいなと思ったら応援しよう!

コメント

ログイン または 会員登録 するとコメントできます。
OpenAIのSwarmアプリケーションのWebUI構築チュートリアル 🚀✨|-D-
word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word

mmMwWLliI0fiflO&1
mmMwWLliI0fiflO&1
mmMwWLliI0fiflO&1
mmMwWLliI0fiflO&1
mmMwWLliI0fiflO&1
mmMwWLliI0fiflO&1
mmMwWLliI0fiflO&1