見出し画像

ChatGPT Pluginsの概要と作成方法


概要

5月12日、来週中にChatGPT Pluginsを全てのChatGPT Plusのユーザに一般公開するという発表が、OpenAI からありました。

それに伴い、本記事では、ChatGPT Pluginsの概要とプラグインの作成方法を解説します。
具体的には、ChatGPTのUIから認証無しで使用可能な、Todoリストプラグインを作成しながら、プラグイン開発の概要を学んでいきます。
また、本記事で紹介する手順では、難しい環境構築無しでプラグインの作成ができるので、エンジニア以外の方も簡単にプラグイン開発が体験できます。
是非試してみてください。

⚠ なお、プラグインの開発には、waitlistに参加する必要がありますので、下記より申請ください。

記事を読むと分かること

  • ChatGPT Pluginsとは

  • ChatGPT Pluginsの作成方法

対象読者

  • ChatGPT Pluginsについて知りたい人

  • ChatGPT Pluginsの作成方法を簡単に把握しておきたい人

ChatGPT Pluginsとは

ChatGPT Pluginsは、ChatGPTとサードパーティーのアプリケーションを接続するためのChatGPTの拡張機能です。
これらのプラグインにより、ChatGPTは開発者によって定義されたAPIと対話することができ、ChatGPTの能力を強化し、広範囲のアクションを実行することができます。
APIの仕様と、それをどのような状況で使うべきかについての記述があれば、モデルはそれに基づいてAPIを活用し、アクションを実行します。
例えば、ユーザーが「パリで2泊3日するならどこに泊まるべきか」と質問した場合、モデルはホテル予約プラグインAPIを利用し、その応答を受け取ります。そして、受け取ったデータと自身の自然言語処理能力を組み合わせて、ユーザー向けの回答を生成します。
また、プラグインを使うと、ChatGPTは以下のようなことが可能になります。

  • リアルタイム情報の取得(スポーツのスコア、株価、最新のニュースなど)

  • ナレッジベース情報の取得(企業のドキュメント、個人のメモなど)

  • ユーザーに代わってアクションを実行すること(フライトの予約、食事の注文など)

このように、ChatGPTプラグインは、ChatGPTをより便利で効率的なものにする新たなツールとなります。
現状は同時に3つのプラグインのみ使用可能ですが、今後、より高度なユースケースに対応できるように進化していくことが予想されます。

プラグインの作成方法

プラグイン開発の全体像

プラグイン開発の流れとしては、大きく下記の3工程に分けられます。
本記事では、以下の流れで、TODOプラグインを作成していきます。

  1. APIの実装

  2. マニフェストファイルの作成

  3. OpenAPIドキュメントの作成

事前準備

  • 開発環境

今回は、ブラウザIDEの「Replit」を使用してプラグインを作成します。
Replit とは、ブラウザIDE(Integrated Development Environment)の1つで、ウェブブラウザ上で動作する統合開発環境のことです。
通常の統合開発環境と同様に、コードの編集、デバッグ、ビルド、実行などの開発作業を一つのツールで行うことができます。

Reaplitの使用方法は以下の通りです。

  1. Replitにサインアップ

  2. Create Replを選択

  3. Pythonを選択

以上の手順ででブラウザ上にPython環境が構築されます。

  • ロゴ画像の配置

プロジェクトのルートディレクトリに logo.png という名前で任意のロゴを配置してください。

1. APIの実装

まず、TODOプラグイン用のAPIを実装していきます。
今回は、公式チュートリアルに沿って、Python の非同期フレームワークである Quartを使用してAPIを構築します。

まずはじめに、requirements.txt を作成し、今回使用するライブラリを記述します。

quart
quart-cors

次に、画面右側のShellタブでに pip install -r requirements.txt コマンドを実行し、上記のライブラリをインストールします。

そして次に、main.py を作成し、APIの処理を実装します。
こちらでは、TODO リストの追加、取得、削除を管理する API を提供しています。

import json

import quart
import quart_cors
from quart import request

app = quart_cors.cors(quart.Quart(__name__),
                      allow_origin="<https://chat.openai.com>")

_TODOS = {}

@app.post("/todos/<string:username>")
async def add_todo(username):
  request = await quart.request.get_json(force=True)
  if username not in _TODOS:
    _TODOS[username] = []
  _TODOS[username].append(request["todo"])
  return quart.Response(response='OK', status=200)

@app.get("/todos/<string:username>")
async def get_todos(username):
  return quart.Response(response=json.dumps(_TODOS.get(username, [])),
                        status=200)

@app.delete("/todos/<string:username>")
async def delete_todo(username):
  request = await quart.request.get_json(force=True)
  todo_idx = request["todo_idx"]
  if 0 <= todo_idx < len(_TODOS[username]):
    _TODOS[username].pop(todo_idx)
  return quart.Response(response='OK', status=200)

@app.get("/logo.png")
async def plugin_logo():
  filename = 'logo.png'
  return await quart.send_file(filename, mimetype='image/png')

@app.get("/.well-known/ai-plugin.json")
async def plugin_manifest():
  host = request.headers['Host']
  with open("./.well-known/ai-plugin.json") as f:
    text = f.read()
    return quart.Response(text, mimetype="text/json")

@app.get("/openapi.yaml")
async def openapi_spec():
  host = request.headers['Host']
  with open("openapi.yaml") as f:
    text = f.read()
    return quart.Response(text, mimetype="text/yaml")

def main():
  app.run(debug=True, host="0.0.0.0", port=5002)

if __name__ == "__main__":
  main()

2. マニフェストファイルの作成

次に、マニフェストファイルを作成します。
マニフェストファイルとは、プラグインの名前やロゴのような基本的な情報(メタデータ)を定義するファイルです。

まず、.well-known フォルダを作成し、 .well-known フォルダ配下に ai-plugin.json ファイルを以下のように定義します。

{
  "schema_version": "v1",
  "name_for_human": "TODO Plugin",
  "name_for_model": "todo",
  "description_for_human": "Plugin for managing a TODO list. You can add, remove and view your TODOs.",
  "description_for_model": "Plugin for managing a TODO list. You can add, remove and view your TODOs.",
  "auth": {
    "type": "none"
  },
  "api": {
    "type": "openapi",
    "url": "<https://todo-plugin--ootaki200109.repl.co/openapi.yaml>",
    "is_user_authenticated": false
  },
  "logo_url": "<https://todo-plugin--ootaki200109.repl.co/logo.png>",
  "contact_email": "support@example.com",
  "legal_info_url": "<http://www.example.com/legal>"
}

マニフェストファイルで特に重要な項目は“description_for_model”です。
“description_for_model”に記載した内容に応じて、自動的にChatGPTがPluginを起動します。
プラグインの説明、リクエスト、レスポンスはChatGPTとの会話の一部とされ、一般的に、モデルには限られたコンテキストウィンドウしかないため、説明とレスポンスをできるだけ簡潔にすることがベストプラクティスです。
“description_for_model” のベストプラクティスの詳細については、以下のリンクを参照してください。

また、マニフェストファイルに定義可能な値の詳細については下記の表をご覧ください。

オプション一覧

3. OpenAPIドキュメントの作成

最後に、OpenAPIドキュメントを設定し定義します。
OpenAPIとは、APIの設計、開発、テスト、文書化を効率化するための標準化されたフレームワークで、APIの仕様書のようなものです。
ChatGPTでクエリが実行されると、infoセクションで定義されている説明文を見て、プラグインがユーザーのクエリに関連しているかどうかを判断します。プロンプトについては、説明文の書き方で詳しく説明しています。
また、ソースコードを自動的にOpenAPI仕様にしてくれるツールもたくさんあるので、必ずしも手動で行う必要はありません。

今回のPythonコードの場合、OpenAPI仕様書は以下のようになります。
ルートディレクトリに openapi.yaml を作成し、以下の設定ファイルを作成してください。

openapi: 3.0.1
info:
  title: TODO Plugin
  description: A plugin that allows the user to create and manage a TODO list using ChatGPT. If you do not know the user's username, ask them first before making queries to the plugin. Otherwise, use the username "global".
  version: "v1"
servers:
  - url: <https://todo-plugin--ootaki200109.repl.co>
paths:
  /todos/{username}:
    get:
      operationId: getTodos
      summary: Get the list of todos
      parameters:
        - in: path
          name: username
          schema:
            type: string
          required: true
          description: The name of the user.
      responses:
        "200":
          description: OK
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/getTodosResponse"
    post:
      operationId: addTodo
      summary: Add a todo to the list
      parameters:
        - in: path
          name: username
          schema:
            type: string
          required: true
          description: The name of the user.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/addTodoRequest"
      responses:
        "200":
          description: OK
    delete:
      operationId: deleteTodo
      summary: Delete a todo from the list
      parameters:
        - in: path
          name: username
          schema:
            type: string
          required: true
          description: The name of the user.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/deleteTodoRequest"
      responses:
        "200":
          description: OK

components:
  schemas:
    getTodosResponse:
      type: object
      properties:
        todos:
          type: array
          items:
            type: string
          description: The list of todos.
    addTodoRequest:
      type: object
      required:
        - todo
      properties:
        todo:
          type: string
          description: The todo to add to the list.
          required: true
    deleteTodoRequest:
      type: object
      required:
        - todo_idx
      properties:
        todo_idx:
          type: integer
          description: The index of the todo to delete.
          required: true

以上で、プラグインの作成は完了です。
最後に、折角なので自身のローカル環境で作成したTODOプラグインを使用してみましょう。

プラグインの導入方法

1. main.pyの実行

Shellに python main.py コマンドを入力し、プログラムを実行します。

2. Pluginの導入

次に、ChatGPTのUIから、Plugin storeにアクセスし、Develop your own pluginを選択します。

次に、自身が設定したport番号に応じたドメインを入力します。今回の場合は localhost:5002 がプラグインのドメインになります。
Install localhost pluginをクリックして、インストール完了です。

動作確認

あとは、自然言語で会話するのみです。実際には以下のようなります。

最後に

この記事では、OpenAIから新たに公開されたChatGPT Pluginの作成方法を解説しました。特に、認証無しで使用可能な、Todoリストの作成・削除ができるTODOプラグインの作成方法を通じて、プラグイン開発の基本的な流れを学びました。
ChatGPT Pluginの登場で、現在のソフトウェアの概念が崩れ、ChatGPT上ですべてのネット上の活動が完結する未来が近々くるかもしれません。

Twitterでも、ChatGPT/AI 関連の情報について発信していきますので、是非フォロー (@ctgptlb)よろしくお願いします。この革命的なテクノロジーの最前線に立つ機会をお見逃しなく!

参考



みんなにも読んでほしいですか?

オススメした記事はフォロワーのタイムラインに表示されます!