このクイックスタート ガイドでは、送信したメッセージにそのまま応答するカスタム エンジン エージェントの作成方法を案内します。
必要条件
Python 3.9 以降。
- Python をインストールするには、https://www.python.org/downloads/にアクセスし、お使いの OS の手順に従ってください。
- バージョンを確認するには、ターミナル ウィンドウで、
python --versionと入力してください。
任意のコード エディター。 これらの手順では Visual Studio Code を使用しています。
Visual Studio Code を使用する場合は、Python 拡張機能をインストールする
プロジェクトを初期化し、SDK をインストールする
Python プロジェクトを作成し、必要な依存関係をインストールします。
ターミナルを開き、新しいフォルダーを作成する
mkdir echo cd echo次のコマンドを実行して、Visual Studio Code でフォルダーを開きます。
code .任意の方法で仮想環境を作成し、Visual Studio Code またはターミナルから有効化します。
Visual Studio Codeを使用する場合は、Python 拡張機能がインストールされていれば、これらの手順を実行できます。
F1 を押し、「
Python: Create environment」と入力して Enter キーを押します。現在のワークスペースで、Venv を選択して
.venv仮想環境を作成します。仮想環境を作成するために Python のインストールを選択します。
値は次のようになります:
Python 1.13.6 ~\AppData\Local\Programs\Python\Python313\python.exe
エージェント SDK をインストールする
pip を使って、microsoft-agents-hosting-aiohttp パッケージを次のコマンドでインストールします:
pip install microsoft-agents-hosting-aiohttp
サーバー アプリケーションを作成し、必要なライブラリをインポートする
start_server.pyというァイルを作成し、次のコードをコピーして、次の場所に貼り付けます:# start_server.py from os import environ from microsoft_agents.hosting.core import AgentApplication, AgentAuthConfiguration from microsoft_agents.hosting.aiohttp import ( start_agent_process, jwt_authorization_middleware, CloudAdapter, ) from aiohttp.web import Request, Response, Application, run_app def start_server( agent_application: AgentApplication, auth_configuration: AgentAuthConfiguration ): async def entry_point(req: Request) -> Response: agent: AgentApplication = req.app["agent_app"] adapter: CloudAdapter = req.app["adapter"] return await start_agent_process( req, agent, adapter, ) APP = Application(middlewares=[jwt_authorization_middleware]) APP.router.add_post("/api/messages", entry_point) APP.router.add_get("/api/messages", lambda _: Response(status=200)) APP["agent_configuration"] = auth_configuration APP["agent_app"] = agent_application APP["adapter"] = agent_application.adapter try: run_app(APP, host="localhost", port=environ.get("PORT", 3978)) except Exception as error: raise errorこのコードは次のファイルで使う
start_server関数を定義しています。同じディレクトリに、次のコードが含まれる
app.pyという名前のファイルを作成します。# app.py from microsoft_agents.hosting.core import ( AgentApplication, TurnState, TurnContext, MemoryStorage, ) from microsoft_agents.hosting.aiohttp import CloudAdapter from start_server import start_server
AgentApplication としてエージェントのインスタンスを作成する
app.py で、AgentApplication のインスタンスとして AGENT_APP を作成し、3 つのイベントに対応する 3 つのルートを実装するための次のコードを追加してください。
- 会話の更新
- メッセージ
/help - その他の活動
AGENT_APP = AgentApplication[TurnState](
storage=MemoryStorage(), adapter=CloudAdapter()
)
async def _help(context: TurnContext, _: TurnState):
await context.send_activity(
"Welcome to the Echo Agent sample 🚀. "
"Type /help for help or send a message to see the echo feature in action."
)
AGENT_APP.conversation_update("membersAdded")(_help)
AGENT_APP.message("/help")(_help)
@AGENT_APP.activity("message")
async def on_message(context: TurnContext, _):
await context.send_activity(f"you said: {context.activity.text}")
Web サーバーを起動して localhost:3978 でリッスンする
app.pyの終わりに、start_server を使って Web サーバーを起動します。
if __name__ == "__main__":
try:
start_server(AGENT_APP, None)
except Exception as error:
raise error
ローカルで匿名モードでエージェントを実行する
ターミナルで次のコマンドを実行してください:
python app.py
ターミナルには次のような出力が表示されます:
======== Running on http://localhost:3978 ========
(Press CTRL+C to quit)
ローカルでエージェントをテストする
別のターミナル (エージェントを実行したままにするため) で、このコマンドを使って Microsoft 365 エージェント プレイグラウンド をインストールしてください:
npm install -g @microsoft/teams-app-test-tool紙幣
このコマンドは npm を使用しています。なぜなら Microsoft 365 エージェント プレイグラウンドは pip で利用できないからです。
ターミナルには次のような出力が表示されます:
added 1 package, and audited 130 packages in 1s 19 packages are looking for funding run `npm fund` for details found 0 vulnerabilities次のコマンドでテスト ツールを起動し、エージェントと対話してください:
teamsapptesterターミナルには次のような出力が表示されます:
Telemetry: agents-playground-cli/serverStart {"cleanProperties":{"options":"{\"configFileOptions\":{\"path\":\"<REDACTED: user-file-path>\"},\"appConfig\":{},\"port\":56150,\"disableTelemetry\":false}"}} Telemetry: agents-playground-cli/cliStart {"cleanProperties":{"isExec":"false","argv":"<REDACTED: user-file-path>,<REDACTED: user-file-path>"}} Listening on 56150 Microsoft 365 Agents Playground is being launched for you to debug the app: http://localhost:56150 started web socket client started web socket client Waiting for connection of endpoint: http://127.0.0.1:3978/api/messages waiting for 1 resources: http://127.0.0.1:3978/api/messages wait-on(37568) complete Telemetry: agents-playground-server/getConfig {"cleanProperties":{"internalConfig":"{\"locale\":\"en-US\",\"localTimezone\":\"America/Los_Angeles\",\"channelId\":\"msteams\"}"}} Telemetry: agents-playground-server/sendActivity {"cleanProperties":{"activityType":"installationUpdate","conversationId":"5305bb42-59c9-4a4c-a2b6-e7a8f4162ede","headers":"{\"x-ms-agents-playground\":\"true\"}"}} Telemetry: agents-playground-server/sendActivity {"cleanProperties":{"activityType":"conversationUpdate","conversationId":"5305bb42-59c9-4a4c-a2b6-e7a8f4162ede","headers":"{\"x-ms-agents-playground\":\"true\"}"}}
teamsapptester コマンドを実行すると、デフォルトのブラウザーが開き、エージェントに接続します。
任意のメッセージを送信してエコー返信を確認できます。また、/help メッセージを送信すると、そのメッセージが _help ハンドラーにどのようにルーティングされるかを確認できます。
このクイックスタート ガイドでは、送信したメッセージにそのまま応答するカスタム エンジン エージェントの作成方法を案内します。
必要条件
Node.js v22 以降
- Node.js をインストールするには、nodejs.org にアクセスし、ご利用の OS の手順に従ってください。
- バージョンを確認するには、ターミナル ウィンドウで、
node --versionと入力してください。
任意のコード エディター。 これらの手順では Visual Studio Code を使用しています。
プロジェクトを初期化し、SDK をインストールする
npm を使って、package.json を作成し、必要な依存関係をインストールして、Node.js プロジェクトを初期化します
ターミナルを開き、新しいフォルダーを作成する
mkdir echo cd echoNode.js プロジェクトを初期化する
npm init -yエージェント SDK をインストールする
npm install @microsoft/agents-hosting-express次のコマンドを使用して、Visual Studio Code でフォルダーを開きます:
code .
必要なライブラリのインポート
ファイル index.mjs を作成し、以下の NPM パッケージをアプリケーション コードにインポートしてください:
// index.mjs
import { startServer } from '@microsoft/agents-hosting-express'
import { AgentApplication, MemoryStorage } from '@microsoft/agents-hosting'
EchoAgent を AgentApplication として実装する
index.mjs で、AgentApplication を拡張する EchoAgent を作成するため、次のコードを追加し、3 つのイベントに対応する 3 つのルートを実装します。
- 会話の更新
- メッセージ
/help - その他の活動
class EchoAgent extends AgentApplication {
constructor (storage) {
super({ storage })
this.onConversationUpdate('membersAdded', this._help)
this.onMessage('/help', this._help)
this.onActivity('message', this._echo)
}
_help = async context =>
await context.sendActivity(`Welcome to the Echo Agent sample 🚀.
Type /help for help or send a message to see the echo feature in action.`)
_echo = async (context, state) => {
let counter= state.getValue('conversation.counter') || 0
await context.sendActivity(`[${counter++}]You said: ${context.activity.text}`)
state.setValue('conversation.counter', counter)
}
}
Web サーバーを起動して localhost:3978 でリッスンする
index.mjs の最後に、Express を基盤とし、ターン ステート ストレージとして MemoryStorage を使用する startServer を使って Web サーバーを起動します。
startServer(new EchoAgent(new MemoryStorage()))
ローカルで匿名モードでエージェントを実行する
ターミナルで次のコマンドを実行してください:
node index.mjs
ターミナルには次の出力が表示されます:
Server listening to port 3978 on sdk 0.6.18 for appId undefined debug undefined
ローカルでエージェントをテストする
別のターミナル (エージェントを実行したままにするため) で、このコマンドを使って Microsoft 365 エージェント プレイグラウンド をインストールしてください:
npm install -D @microsoft/teams-app-test-toolターミナルには次のような出力が表示されます:
added 1 package, and audited 130 packages in 1s 19 packages are looking for funding run `npm fund` for details found 0 vulnerabilities次のコマンドでテスト ツールを起動し、エージェントと対話してください:
node_modules/.bin/teamsapptesterターミナルには次のような出力が表示されます:
Telemetry: agents-playground-cli/serverStart {"cleanProperties":{"options":"{\"configFileOptions\":{\"path\":\"<REDACTED: user-file-path>\"},\"appConfig\":{},\"port\":56150,\"disableTelemetry\":false}"}} Telemetry: agents-playground-cli/cliStart {"cleanProperties":{"isExec":"false","argv":"<REDACTED: user-file-path>,<REDACTED: user-file-path>"}} Listening on 56150 Microsoft 365 Agents Playground is being launched for you to debug the app: http://localhost:56150 started web socket client started web socket client Waiting for connection of endpoint: http://127.0.0.1:3978/api/messages waiting for 1 resources: http://127.0.0.1:3978/api/messages wait-on(37568) complete Telemetry: agents-playground-server/getConfig {"cleanProperties":{"internalConfig":"{\"locale\":\"en-US\",\"localTimezone\":\"America/Los_Angeles\",\"channelId\":\"msteams\"}"}} Telemetry: agents-playground-server/sendActivity {"cleanProperties":{"activityType":"installationUpdate","conversationId":"5305bb42-59c9-4a4c-a2b6-e7a8f4162ede","headers":"{\"x-ms-agents-playground\":\"true\"}"}} Telemetry: agents-playground-server/sendActivity {"cleanProperties":{"activityType":"conversationUpdate","conversationId":"5305bb42-59c9-4a4c-a2b6-e7a8f4162ede","headers":"{\"x-ms-agents-playground\":\"true\"}"}}
teamsapptester コマンドを実行すると、デフォルトのブラウザーが開き、エージェントに接続します。
任意のメッセージを送信してエコー返信を確認できます。また、/help メッセージを送信すると、そのメッセージが _help ハンドラーにどのようにルーティングされるかを確認できます。
このクイックスタート ガイドでは、送信したメッセージにそのまま応答するカスタム エンジン エージェントの作成方法を案内します。
必要条件
.NET 8.0 SDK 以上
- .NET SDK をインストールするには、dotnet.microsoft.com にアクセスし、ご利用のオペレーティング システムの手順に従ってください。
- バージョンを確認するには、ターミナル ウィンドウで、
dotnet --versionと入力してください。
任意のコード エディター。 これらの手順では Visual Studio Code を使用しています。
プロジェクトを初期化し、SDK をインストールする
dotnet を使って新しい Web プロジェクトを作成し、必要な依存関係をインストールします。
ターミナルを開き、新しいフォルダーを作成する
mkdir echo cd echo.NET プロジェクトを初期化する
dotnet new webエージェント SDK をインストールする
dotnet add package Microsoft.Agents.Hosting.AspNetCore次のコマンドを実行して、Visual Studio Code でフォルダーを開きます。
code .
必要なライブラリのインポート
Program.cs の内容を置き換え、SDK パッケージをアプリケーション コードにインポートするために、次の using 行を追加してください。
// Program.cs
using Microsoft.Agents.Builder;
using Microsoft.Agents.Builder.App;
using Microsoft.Agents.Builder.State;
using Microsoft.Agents.Core.Models;
using Microsoft.Agents.Hosting.AspNetCore;
using Microsoft.Agents.Storage;
using Microsoft.AspNetCore.Builder;
EchoAgent を AgentApplication として実装する
Program.cs の using 文の後に、AgentApplication を拡張した EchoAgent を作成し、イベントに応答するルートを実装するための次のコードを追加してください。
- 会話の更新
- その他の活動
public class EchoAgent : AgentApplication
{
public EchoAgent(AgentApplicationOptions options) : base(options)
{
OnConversationUpdate(ConversationUpdateEvents.MembersAdded, WelcomeMessageAsync);
OnActivity(ActivityTypes.Message, OnMessageAsync, rank: RouteRank.Last);
}
private async Task WelcomeMessageAsync(ITurnContext turnContext, ITurnState turnState, CancellationToken cancellationToken)
{
foreach (ChannelAccount member in turnContext.Activity.MembersAdded)
{
if (member.Id != turnContext.Activity.Recipient.Id)
{
await turnContext.SendActivityAsync(MessageFactory.Text("Hello and Welcome!"), cancellationToken);
}
}
}
private async Task OnMessageAsync(ITurnContext turnContext, ITurnState turnState, CancellationToken cancellationToken)
{
await turnContext.SendActivityAsync($"You said: {turnContext.Activity.Text}", cancellationToken: cancellationToken);
}
}
Web サーバーを設定して、エージェント アプリケーションを登録する
Program.cs で、using の後に、Web ホストを設定し、エージェントを登録し、/api/messages エンドポイントをマッピングするための次のコードを追加してください。
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddHttpClient();
builder.AddAgentApplicationOptions();
builder.AddAgent<EchoAgent>();
builder.Services.AddSingleton<IStorage, MemoryStorage>();
var app = builder.Build();
app.MapPost("/api/messages", async (HttpRequest request, HttpResponse response, IAgentHttpAdapter adapter, IAgent agent, CancellationToken cancellationToken) =>
{
await adapter.ProcessAsync(request, response, agent, cancellationToken);
});
app.Run();
Web サーバーが localhost:3978 でリッスンするように設定する
launchSettings.json の applicationURL を http://localhost:3978 に変更し、アプリが正しいポートでリッスンするように設定します。
ローカルで匿名モードでエージェントを実行する
ターミナルで次のコマンドを実行してください:
dotnet run
ターミナルには次のような出力が表示されます:
info: Microsoft.Hosting.Lifetime[14]
Now listening on: http://localhost:3978
ローカルでエージェントをテストする
別のターミナル (エージェントを動作させたままにするために) で、次のコマンドを使って Microsoft 365 エージェント プレイグラウンドをインストールします。
npm install -g @microsoft/teams-app-test-tool紙幣
このコマンドは、Microsoft 365 エージェント プレイグラウンドが npm パッケージとして配布されているため、npm を使用しています。
ターミナルには次のような出力が表示されます:
added 1 package, and audited 130 packages in 1s 19 packages are looking for funding run `npm fund` for details found 0 vulnerabilities次のコマンドでテスト ツールを起動し、エージェントと対話してください:
teamsapptesterターミナルには次のような出力が表示されます:
Telemetry: agents-playground-cli/serverStart {"cleanProperties":{"options":"{\"configFileOptions\":{\"path\":\"<REDACTED: user-file-path>\"},\"appConfig\":{},\"port\":56150,\"disableTelemetry\":false}"}} Telemetry: agents-playground-cli/cliStart {"cleanProperties":{"isExec":"false","argv":"<REDACTED: user-file-path>,<REDACTED: user-file-path>"}} Listening on 56150 Microsoft 365 Agents Playground is being launched for you to debug the app: http://localhost:56150 started web socket client started web socket client Waiting for connection of endpoint: http://127.0.0.1:3978/api/messages waiting for 1 resources: http://127.0.0.1:3978/api/messages wait-on(37568) complete Telemetry: agents-playground-server/getConfig {"cleanProperties":{"internalConfig":"{\"locale\":\"en-US\",\"localTimezone\":\"America/Los_Angeles\",\"channelId\":\"msteams\"}"}} Telemetry: agents-playground-server/sendActivity {"cleanProperties":{"activityType":"installationUpdate","conversationId":"5305bb42-59c9-4a4c-a2b6-e7a8f4162ede","headers":"{\"x-ms-agents-playground\":\"true\"}"}} Telemetry: agents-playground-server/sendActivity {"cleanProperties":{"activityType":"conversationUpdate","conversationId":"5305bb42-59c9-4a4c-a2b6-e7a8f4162ede","headers":"{\"x-ms-agents-playground\":\"true\"}"}}
teamsapptester コマンドを実行すると、デフォルトのブラウザーが開き、エージェントに接続します。
テキスト入力に任意のメッセージを入力して送信すると、エコーの返信が表示されます。
次の手順
- GitHub で Agents SDK のサンプルを確認する
- 活動について、また活動の操作方法について詳しく学ぶ
- クライアントから対応できる AgentApplication イベントを確認する
- クライアントに送信できる TurnContext イベントを確認する
- Agents SDK 用の Azure ボット リソースをプロビジョニングする
- .NET エージェントを構成してOAuth を使用する
すでに Microsoft 365 エージェント ツール キットを使用している場合、エージェント プレイグラウンドはデフォルトで利用可能です。 ツール キットの利用を始めるには、以下のガイドのいずれかを参照してください: