OpenAPI 仕様からプラグインを追加する

多くの場合、企業には、実際の作業を実行する API のセットが既にあります。 これらは、人間が操作する他のオートメーション サービスや電源フロントエンド アプリケーションで使用できます。 セマンティック カーネルでは、これらのプラグインとまったく同じ API を追加して、エージェントで使用することもできます。

OpenAPI 仕様の例

たとえば、電球の状態を変更できる API を使用します。 この API の OpenAPI 仕様は次のようになります。

{
   "openapi": "3.0.1",
   "info": {
      "title": "Light API",
      "version": "v1"
   },
   "paths": {
      "/Light": {
         "get": {
            "tags": [
               "Light"
            ],
            "summary": "Retrieves all lights in the system.",
            "operationId": "get_all_lights",
            "responses": {
               "200": {
                  "description": "Returns a list of lights with their current state",
                  "application/json": {
                     "schema": {
                        "type": "array",
                        "items": {
                              "$ref": "#/components/schemas/LightStateModel"
                        }
                     }
                  }
               }
            }
         }
      },
      "/Light/{id}": {
         "post": {
               "tags": [
                  "Light"
               ],
               "summary": "Changes the state of a light.",
               "operationId": "change_light_state",
               "parameters": [
                  {
                     "name": "id",
                     "in": "path",
                     "description": "The ID of the light to change from the get_all_lights tool.",
                     "required": true,
                     "style": "simple",
                     "schema": {
                           "type": "string"
                     }
                  }
               ],
               "requestBody": {
                  "description": "The new state of the light and change parameters.",
                  "content": {
                     "application/json": {
                           "schema": {
                              "$ref": "#/components/schemas/ChangeStateRequest"
                           }
                     }
                  }
               },
               "responses": {
                  "200": {
                     "description": "Returns the updated light state",
                     "content": {
                           "application/json": {
                              "schema": {
                                 "$ref": "#/components/schemas/LightStateModel"
                              }
                           }
                     }
                  },
                  "404": {
                     "description": "If the light is not found"
                  }
               }
         }
      }
   },
   "components": {
      "schemas": {
         "ChangeStateRequest": {
               "type": "object",
               "properties": {
                  "isOn": {
                     "type": "boolean",
                     "description": "Specifies whether the light is turned on or off.",
                     "nullable": true
                  },
                  "hexColor": {
                     "type": "string",
                     "description": "The hex color code for the light.",
                     "nullable": true
                  },
                  "brightness": {
                     "type": "integer",
                     "description": "The brightness level of the light.",
                     "format": "int32",
                     "nullable": true
                  },
                  "fadeDurationInMilliseconds": {
                     "type": "integer",
                     "description": "Duration for the light to fade to the new state, in milliseconds.",
                     "format": "int32",
                     "nullable": true
                  },
                  "scheduledTime": {
                     "type": "string",
                     "description": "Use ScheduledTime to synchronize lights. It's recommended that you asynchronously create tasks for each light that's scheduled to avoid blocking the main thread.",
                     "format": "date-time",
                     "nullable": true
                  }
               },
               "additionalProperties": false,
               "description": "Represents a request to change the state of the light."
         },
         "LightStateModel": {
               "type": "object",
               "properties": {
                  "id": {
                     "type": "string",
                     "nullable": true
                  },
                  "name": {
                     "type": "string",
                     "nullable": true
                  },
                  "on": {
                     "type": "boolean",
                     "nullable": true
                  },
                  "brightness": {
                     "type": "integer",
                     "format": "int32",
                     "nullable": true
                  },
                  "hexColor": {
                     "type": "string",
                     "nullable": true
                  }
               },
               "additionalProperties": false
         }
      }
   }
}

この仕様では、API とその操作方法を理解するために AI に必要なすべてのものが提供されます。 API には、2 つのエンドポイントが含まれています。1 つはすべてのライトを取得し、もう 1 つはライトの状態を変更するエンドポイントです。 また、次の機能も提供します。

  • エンドポイントとそのパラメーターのセマンティックの説明
  • パラメーターの型
  • 予想される応答

AI エージェントはこの仕様を理解できるため、エージェントにプラグインとして追加できます。

ヒント

既存の OpenAPI 仕様がある場合は、AI で理解しやすくするために変更が必要になる場合があります。 たとえば、説明にガイダンスを提供することが必要な場合があります。 OpenAPI 仕様を AI に対応させる方法に関するその他のヒントについては、「 Tips and tricks for adding OpenAPI pluginsを参照してください。

OpenAPI プラグインの追加

数行のコードを使用して、OpenAPI プラグインをエージェントに追加できます。 次のコード スニペットは、上記の OpenAPI 仕様からライト プラグインを追加する方法を示しています。

await kernel.ImportPluginFromOpenApiAsync(
   pluginName: "lights",
   uri: new Uri("https://example.com/v1/swagger.json"),
   executionParameters: new OpenApiFunctionExecutionParameters()
   {
      // Determines whether payload parameter names are augmented with namespaces.
      // Namespaces prevent naming conflicts by adding the parent parameter name
      // as a prefix, separated by dots
      EnablePayloadNamespacing = true
   }
);
await kernel.add_plugin_from_openapi(
   plugin_name="lights",
   openapi_document_path="https://example.com/v1/swagger.json",
   execution_settings=OpenAPIFunctionExecutionParameters(
         # Determines whether payload parameter names are augmented with namespaces.
         # Namespaces prevent naming conflicts by adding the parent parameter name
         # as a prefix, separated by dots
         enable_payload_namespacing=True,
   ),
)
String yaml = EmbeddedResourceLoader.readFile("petstore.yaml", ExamplePetstoreImporter.class);

KernelPlugin plugin = SemanticKernelOpenAPIImporter
   .builder()
   .withPluginName("petstore")
   .withSchema(yaml)
   .withServer("http://localhost:8090/api/v3")
   .build();

Kernel kernel = ExampleOpenAPIParent.kernelBuilder()
   .withPlugin(plugin)
   .build();

その後、ネイティブ プラグインであるかのように、エージェントでプラグインを使用できます。

OpenAPI プラグインを追加するためのヒントとテクニック

OpenAPI 仕様は通常、人間向けに設計されているため、AI が理解しやすくするためにいくつかの変更が必要になる場合があります。 これを行う際に役立つヒントとテクニックを次に示します。

推奨 説明
API の仕様をバージョン管理する ライブ API 仕様を指す代わりに、Swagger ファイルのチェックインとバージョン管理を検討してください。 これにより、AI 研究者は、ライブ API に影響を与えずに、AI エージェントによって使用される API 仕様をテスト (および変更) できるようになります。
エンドポイントの数を制限する API 内のエンドポイントの数を制限してみてください。 複雑さを軽減するために、省略可能なパラメーターを使用して、同様の機能を単一のエンドポイントに統合します。
エンドポイントとパラメーターにわかりやすい名前を使用する エンドポイントとパラメーターの名前がわかりやすいわかりやすいものになっていることを確認します。 これは、AI が広範な説明を必要とせずに目的を理解するのに役立ちます。
一貫性のある名前付け規則を使用する API 全体で一貫した名前付け規則を維持します。 これにより、混乱が軽減され、AI が API の構造をより簡単に学習して予測するのに役立ちます。
API の仕様を簡略化する 多くの場合、OpenAPI 仕様は非常に詳細であり、AI エージェントがユーザーを支援するために必要ではない多くの情報を含みます。 API が単純な場合、API の記述に費やすトークンの数が少ないほど、AI が要求を送信するために必要なトークンも少なくなります。
文字列パラメーターを使用しないようにする 可能な場合は、API で文字列パラメーターを使用しないでください。 代わりに、整数、ブール値、列挙型などのより具体的な型を使用します。 これは、AI が API をよりよく理解するのに役立ちます。
説明に例を入力する 人間が Swagger ファイルを使用する場合、通常、サンプルの要求と応答を含む Swagger UI を使用して API をテストできます。 AI エージェントではこれを行えないので、パラメーターの説明に例を提供することを検討してください。
説明で他のエンドポイントを参照する 多くの場合、AI は同様のエンドポイントを混乱させます。 AI がエンドポイントを区別できるように、説明の他のエンドポイントを参照することを検討してください。 たとえば、"このエンドポイントは get_all_lights エンドポイントに似ていますが、単一のライトのみを返します" と言います。
役に立つエラー メッセージを提供する OpenAPI 仕様には含まれていませんが、AI の自己修正に役立つエラー メッセージを提供することを検討してください。 たとえば、ユーザーが無効な ID を指定した場合は、ai エージェントが get_all_lights エンドポイントから正しい ID を取得することを示すエラー メッセージを提供することを検討してください。

次のステップ

プラグインを作成する方法がわかったら、AI エージェントでプラグインを使用する方法を学習できるようになりました。 プラグインに追加した関数の種類に応じて、従う必要があるパターンが異なります。 取得関数については、 取得関数の使用に関する記事 参照してください。 タスク自動化関数については、 タスク自動化関数の使用に関する記事 参照してください。