本快速入門將引導您建立 自訂引擎代理程式 ,以回覆您傳送給它的任何訊息。
先決條件
Python 3.9 或更新版本。
- 若要安裝 Python,請移至 https://www.python.org/downloads/,然後按照作業系統的指示進行操作。
- 若要驗證版本,請在終端機視窗中鍵入
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
安裝 Agents 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中新增以下程式碼,建立 作為 AGENT_APP 的實例 AgentApplication,並實作三個路由來回應三個事件:
- 對話更新
- 訊息
/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}")
啟動網路伺服器以在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)
在本機測試 Agent
從另一個終端機 (讓 Agent 持續執行),使用下列命令安裝 Microsoft 365 Agents 遊樂場:
npm install -g @microsoft/teams-app-test-tool備註
此命令會使用 npm,因為無法使用 pip 使用 Microsoft 365 代理程式遊樂場。
終端機應該會傳回如下的內容:
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,然後按照作業系統的指示進行操作。
- 若要驗證版本,請在終端機視窗中鍵入
node --version。
您選擇的程式代碼編輯器。 這些指示使用 Visual Studio Code。
初始化專案並安裝 SDK
使用 npm 來建立 package.json 並安裝必要的相依性,以初始化 node.js 專案
開啟終端機並建立新資料夾
mkdir echo cd echo初始化 node.js 專案
npm init -y安裝 Agents 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,新增下列程式代碼來建立 EchoAgent 擴充 AgentApplication,並實作三個路由以回應三個事件:
- 對話更新
- 訊息
/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)
}
}
啟動網路伺服器以在localhost:3978上進行監聽
在 index.mjs 結尾,根據使用 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
在本機測試 Agent
從另一個終端機 (讓 Agent 持續執行),使用下列命令安裝 Microsoft 365 Agents 遊樂場:
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 處理程式。
後續步驟
這個快速入門會示範如何從 GitHub 下載並執行 QuickStart/Empty Agent 範例。
有兩種主要方式可以開始使用 Microsoft 365 代理程式 SDK:
複製並執行 GitHub 上提供的 QuickStart/Empty Agent 代理程式範例
使用 Microsoft 365 Agents Toolkit。 代理程式工具組提供兩個內建範本給 Visual Studio 和 Visual Studio Code,採用 Microsoft 365 代理程式 SDK。使用這些範本可以開始建立快速入門或空代理程式,以及利用 Azure Foundry 或 OpenAI 服務搭配 Semantic Kernel 或 LangChain 的天氣代理程式。
先決條件
開始之前,您需要一些事項。 這些步驟會使用 .NET 快速入門中的快速入門/空代理程式範例,但您也可以使用任何 代理程式 SDK 範例。
- .NET 8.0 SDK
- Visual Studio 或 Visual Studio Code
- ASP.NET Core 和 C# 中的非同步的程式設計知識
- 從 GitHub 下載
quickstart範例
開啟解決方案
在 Visual Studio 中開啟方案檔
QuickStart.csproj。執行專案。
此時,您的 Agent 會使用連接埠 3978 在本機執行。
在本機測試您的代理程式
如果您尚未安裝 Agents Playground,請安裝。
winget install agentsplayground在 Visual Studio 或 Visual Studio Code 中啟動代理程式
啟動 Teams 應用程式測試器。 在命令提示字元中:
agentsplayground- 此工具會開啟顯示 Teams 應用程式測試工具的網頁瀏覽器,準備將訊息傳送給您的代理程式。
您在連接埠 3978 上執行的代理程式應該會自動連線到瀏覽器中的代理程式遊樂場,並且您應該能夠與在本機執行的代理程式互動
代理程式如何運作?
使用 Agents SDK 時,代理程式是使用 AgentApplication 和 AgentApplicationOptions 類別建置的。 這是建置在範例的 Program.cs 檔案中。
建立您的 Agent
您可以在範例中看到,當代理程式正在建置時,會載入 AgentApplicationOptions,以及繼承自 MyAgent.cs 的自訂代理類別 AgentApplication。
// Add AgentApplicationOptions from appsettings section "AgentApplication".
builder.AddAgentApplicationOptions();
// Add the AgentApplication, which contains the logic for responding to
// user messages.
builder.AddAgent<MyAgent>();
然後,預設會使用 MemoryStorage 類別載入儲存體。 這可讓您在使用TurnState時追蹤跨回合的上下文,但應在生產環境中切換,以取得持久性儲存,例如Blob儲存體或Cosmos DB分區儲存體。
builder.Services.AddSingleton<IStorage, MemoryStorage>();
代理程式應用程式的其餘部分會使用標準 .NET 裝載模式,並新增路由以接受特定端點的訊息。 這些路由會使用 IAgent 介面 來接受代理程式活動,並為開發人員提供 AgentApplication 物件,以使用從通道/用戶端傳遞給它的 活動 承載。
深入瞭解活動和使用活動
// This receives incoming messages from Azure Bot Service or other SDK Agents
var incomingRoute = app.MapPost("/api/messages", async (HttpRequest request, HttpResponse response, IAgentHttpAdapter adapter, IAgent agent, CancellationToken cancellationToken) =>
{
await adapter.ProcessAsync(request, response, agent, cancellationToken);
});
在方法中新增自訂邏輯
開發人員在實作MyAgent.cs的AgentApplication類別中新增自訂邏輯。 此類別使用 AgentApplicationOptions 來配置您配置中的任何特定設定,並使用 Program.cs 從代理 SDK 註冊事件監聽器。這些監聽器會在從客戶端觸發事件時,參考 AgentApplication 類別中您各自的自訂方法。
在下列範例中, OnConversationUpdate 會 WelcomeMessageAsync 觸發方法, 而 OnActivity 會觸發方法 OnMessageAsync。
public MyAgent(AgentApplicationOptions options) : base(options)
{
OnConversationUpdate(ConversationUpdateEvents.MembersAdded, WelcomeMessageAsync);
OnActivity(ActivityTypes.Message, OnMessageAsync, rank: RouteRank.Last);
}
這些事件會透過您 MyProgram.cs 中設定的端點路由,而且您可以使用許多事件。 最常見的是 OnActivity。 若要進一步瞭解 SDK 實作的事件,請參閱有關 使用活動 和 活動通訊協定規格的詳細資訊。
觸發方法後,例如在自訂邏輯中選擇使用 OnMessageAsync 來結束回合,您可以使用 TurnContext 類別 的實例中可用的方法來回傳訊息給用戶端,此類別應作為您方法中的參數,如以下範例所示:
private async Task OnMessageAsync(ITurnContext turnContext, ITurnState turnState, CancellationToken cancellationToken)
{
await turnContext.SendActivityAsync($"You said: {turnContext.Activity.Text}", cancellationToken: cancellationToken);
}
小提示
檢閱其他可用來傳回用戶端的 TurnContext 方法 。
現在您了解了基本知識,請查看後續步驟,並努力將自訂處理常式邏輯新增至您的代理程式並傳回不同的事件。
後續步驟
- 深入瞭解活動和使用活動
- 檢視您可以從用戶端回應的 AgentApplication 事件
- 檢閱您可以傳回用戶端的 TurnContext 事件
- 佈建 Azure Bot 資源以與代理程式 SDK 搭配使用
- 設定 .NET 代理程式以使用 OAuth
如果您已經使用 Microsoft 365 Agents Toolkit,則預設可以使用 Agents 遊樂場。 如果您要開始使用工具組,可以使用下列其中一個指南: