แชร์ผ่าน


เริ่มต้นใช้งานด่วน: สร้างและทดสอบตัวแทนพื้นฐาน

การเริ่มต้นใช้งานด่วนนี้จะแนะนําคุณในการสร้าง ตัวแทนกลไกจัดการแบบกําหนดเอง ที่ตอบกลับด้วยข้อความใดก็ตามที่คุณส่งไป

ข้อกําหนดเบื้องต้น

  • Python 3.9 หรือใหม่กว่า

    • เมื่อต้องการติดตั้ง Python ให้ไปที่ https://www.python.org/downloads/และทําตามคําแนะนําสําหรับระบบปฏิบัติการของคุณ
    • เมื่อต้องการตรวจสอบเวอร์ชัน ในชนิด python --versionหน้าต่างเทอร์มินัล
  • ตัวแก้ไขโค้ดที่คุณเลือก คําแนะนําเหล่านี้ใช้ Visual Studio Code

    หากคุณใช้ Visual Studio Code ให้ติดตั้ง ส่วนขยาย Python

เริ่มต้นโครงการและติดตั้ง SDK

สร้างโครงการ Python และติดตั้งการขึ้นต่อกันที่จําเป็น

  1. เปิดเทอร์มินัลและสร้างโฟลเดอร์ใหม่

    mkdir echo
    cd echo
    
  2. เปิดโฟลเดอร์โดยใช้รหัส Visual Studio โดยใช้คําสั่งนี้:

    code .
    
  3. สร้างสภาพแวดล้อมเสมือนด้วยวิธีการที่คุณเลือกและเปิดใช้งานผ่าน Visual Studio Code หรือในเทอร์มินัล

    เมื่อใช้ Visual Studio Code คุณสามารถใช้ขั้นตอนเหล่านี้กับ ส่วนขยาย Python ที่ติดตั้งไว้

    1. กด F1 พิมพ์ Python: Create environmentและกด Enter

      1. เลือก Venv เพื่อสร้าง .venv สภาพแวดล้อมเสมือนในพื้นที่ทํางานปัจจุบัน

      2. เลือกการติดตั้ง Python เพื่อสร้างสภาพแวดล้อมเสมือน

        ค่าอาจมีลักษณะดังนี้:

        Python 1.13.6 ~\AppData\Local\Programs\Python\Python313\python.exe

  4. ติดตั้ง Agents SDK

    ใช้ pip เพื่อติดตั้งแพคเกจ microsoft-agents-hosting-aiohttp ด้วยคําสั่งนี้:

    pip install microsoft-agents-hosting-aiohttp
    

สร้างแอปพลิเคชันเซิร์ฟเวอร์และนําเข้าไลบรารีที่จําเป็น

  1. สร้างไฟล์ที่ชื่อ คัดลอก 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 ฟังก์ชันที่เราจะใช้ในไฟล์ถัดไป

  2. ในไดเรกทอรีเดียวกัน สร้างไฟล์ที่ 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
    

สร้างอินสแตนซ์ของ Agent เป็น 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

if __name__ == "__main__":
    try:
        start_server(AGENT_APP, None)
    except Exception as error:
        raise error

เรียกใช้ Agent ภายในเครื่องในโหมดไม่ระบุชื่อ

จากเทอร์มินัลของคุณ ให้เรียกใช้คําสั่งนี้:

python app.py

เทอร์มินัลควรส่งกลับรายการต่อไปนี้:

======== Running on http://localhost:3978 ========
(Press CTRL+C to quit)

ทดสอบเอเจนต์ภายในเครื่อง

  1. จากเทอร์มินัลอื่น (เพื่อให้ตัวแทนทํางาน) ติดตั้ง Microsoft 365 Agents Playground ด้วยคําสั่งนี้:

    npm install -g @microsoft/teams-app-test-tool
    

    Note

    คําสั่งนี้ใช้ npm เนื่องจาก Microsoft 365 Agents Playground ไม่พร้อมใช้งานโดยใช้ pip

    เทอร์มินัลควรส่งกลับบางอย่างเช่น:

    added 1 package, and audited 130 packages in 1s
    
    19 packages are looking for funding
    run `npm fund` for details
    
    found 0 vulnerabilities
    
  2. เรียกใช้เครื่องมือทดสอบเพื่อโต้ตอบกับตัวแทนของคุณโดยใช้คําสั่งนี้:

    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 เปิดเบราว์เซอร์เริ่มต้นของคุณและเชื่อมต่อกับตัวแทนของคุณ

เอเจนต์ของคุณใน Agents Playground

ในตอนนี้ คุณสามารถส่งข้อความเพื่อดูการตอบกลับ echo หรือส่งข้อความ /help เพื่อดูว่าข้อความนั้นถูกส่งไปยัง _help ตัวจัดการได้อย่างไร

ขั้นตอนถัดไป

เตรียมใช้ทรัพยากร Azure Bot เพื่อใช้กับ Agents SDK

การเริ่มต้นใช้งานด่วนนี้จะแนะนําคุณในการสร้าง ตัวแทนเครื่องมือแบบกําหนดเอง ที่เพียงแค่ตอบกลับด้วยอะไรก็ตามที่คุณส่งไป

ข้อกําหนดเบื้องต้น

  • Node.js v22 หรือใหม่กว่า

    • เมื่อต้องการติดตั้ง Node.js ให้ไปที่ nodejs.org แล้วทําตามคําแนะนําสําหรับระบบปฏิบัติการของคุณ
    • เมื่อต้องการตรวจสอบเวอร์ชัน ในชนิด node --versionหน้าต่างเทอร์มินัล
  • ตัวแก้ไขโค้ดที่คุณเลือก คําแนะนําเหล่านี้ใช้ Visual Studio Code

เริ่มต้นโครงการและติดตั้ง SDK

ใช้ npm เพื่อเริ่มต้นโครงการ node.js โดยการสร้าง package.json และติดตั้งการขึ้นต่อกันที่จําเป็น

  1. เปิดเทอร์มินัลและสร้างโฟลเดอร์ใหม่

    mkdir echo
    cd echo
    
  2. เตรียมใช้งานโครงการ node.js

    npm init -y
    
  3. ติดตั้ง Agents SDK

    npm install @microsoft/agents-hosting-express
    
  4. เปิดโฟลเดอร์โดยใช้ Visual Studio Code โดยใช้คําสั่งนี้:

    code .
    

นําเข้าไลบรารีที่จําเป็น

สร้างไฟล์ index.mjs และนําเข้าแพคเกจ NPM ต่อไปนี้ลงในรหัสแอปพลิเคชันของคุณ:

// index.mjs
import { startServer } from '@microsoft/agents-hosting-express'
import { AgentApplication, MemoryStorage } from '@microsoft/agents-hosting'

ใช้ EchoAgent เป็นตัวแทนแอป

ใน 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 เริ่มต้นเว็บเซิร์ฟเวอร์โดยใช้ startServer ตาม Express และใช้ MemoryStorage เป็นที่เก็บการเปลี่ยนแปลงสถานะ

startServer(new EchoAgent(new MemoryStorage()))

เรียกใช้ Agent ภายในเครื่องในโหมดไม่ระบุชื่อ

จากเทอร์มินัลของคุณ ให้เรียกใช้คําสั่งนี้:

node index.mjs

เทอร์มินัลควรส่งกลับค่านี้:

Server listening to port 3978 on sdk 0.6.18 for appId undefined debug undefined

ทดสอบเอเจนต์ภายในเครื่อง

  1. จากเทอร์มินัลอื่น (เพื่อให้ตัวแทนทํางาน) ติดตั้ง Microsoft 365 Agents Playground ด้วยคําสั่งนี้:

    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
    
  2. เรียกใช้เครื่องมือทดสอบเพื่อโต้ตอบกับตัวแทนของคุณโดยใช้คําสั่งนี้:

    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 เปิดเบราว์เซอร์เริ่มต้นของคุณและเชื่อมต่อกับตัวแทนของคุณ

เอเจนต์ของคุณใน Agents Playground

ในตอนนี้ คุณสามารถส่งข้อความเพื่อดูการตอบกลับ echo หรือส่งข้อความ /help เพื่อดูว่าข้อความนั้นถูกส่งไปยัง _help ตัวจัดการได้อย่างไร

ขั้นตอนถัดไป

เตรียมใช้ทรัพยากร Azure Bot เพื่อใช้กับ Agents SDK

การเริ่มต้นฉบับย่อนี้แสดงวิธีดาวน์โหลดและเรียกใช้ตัวอย่าง QuickStart/Empty Agent จาก GitHub

มีสองวิธีหลักในการเริ่มต้นใช้งาน Microsoft 365 Agents SDK:

  • ลอกแบบและเรียกใช้ตัวอย่าง QuickStart/Empty Agent ที่พร้อมใช้งานบน GitHub

  • ใช้ชุดเครื่องมือตัวแทนของ Microsoft 365 ชุดเครื่องมือตัวแทนมีเทมเพลตสำเร็จรูปสองเทมเพลตสำหรับ Visual Studio และ Visual Studio Code ที่ใช้ SDK ของ Microsoft 365 Agents สำหรับเริ่มต้นด้วย QuickStart/Empty Agent และตัวแทนสภาพอากาศที่ใช้ Azure Foundry หรือ OpenAI Services ร่วมกับ Semantic Kernel หรือ LangChain

ข้อกําหนดเบื้องต้น

คุณจําเป็นต้องมีบางสิ่งก่อนที่คุณจะเริ่มต้นใช้งาน ขั้นตอนเหล่านี้ใช้ตัวอย่าง QuickStart/Empty Agent ที่ .NET quickstart แต่คุณยังสามารถใช้ ตัวอย่าง Agents SDK ใด ๆ ได้

เปิดโซลูชัน

  1. เปิดไฟล์ QuickStart.csproj โซลูชันใน Visual Studio

  2. เรียกใช้โครงการ

ในตอนนี้ ตัวแทนของคุณกําลังทํางานภายในเครื่องโดยใช้พอร์ต 3978

ทดสอบเอเจนต์ภายในระบบของคุณ

  1. ติดตั้ง Agents Playground หากคุณยังไม่ได้ติดตั้ง

    winget install agentsplayground
    
  2. เริ่มต้นตัวแทนใน Visual Studio หรือ Visual Studio Code

  3. เริ่มตัวทดสอบแอป Teams ที่พร้อมท์คำสั่ง: agentsplayground

    • เครื่องมือนี้เปิดเว็บเบราว์เซอร์ที่แสดงเครื่องมือทดสอบแอป Teams พร้อมที่จะส่งข้อความถึงตัวแทนของคุณ
  4. ตัวแทนที่ทํางานบนพอร์ต 3978 ควรเชื่อมต่อโดยอัตโนมัติกับตัวแทน playground ในเบราว์เซอร์ของคุณ และคุณควรสามารถโต้ตอบกับตัวแทนที่ทํางานภายในเครื่องของคุณ

เอเย่นต์ทํางานอย่างไร?

ด้วย Agents SDK ตัวแทนถูกสร้างขึ้นโดยใช้คลาส AgentApplication และ AgentApplicationOptions ซึ่งถูกสร้างขึ้นใน Program.cs ไฟล์ของตัวอย่าง

สร้างตัวแทนของคุณ

คุณสามารถดูตัวอย่างได้ว่า ขณะที่กำลังสร้างตัวแทน 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 อย่างไรก็ตามควรสลับออกไปในการผลิตเพื่อเก็บข้อมูลที่คงอยู่มากขึ้น เช่น BlobsStorage หรือ CosmosDbPartitionedStorage

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 เพื่อกำหนดค่าตั้งค่าเฉพาะจากการตั้งค่า config ของคุณ และ Program.cs ในการลงทะเบียนตัวฟังเหตุการณ์จาก Agents 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 อื่นที่พร้อมใช้งานเพื่อกลับไปยังไคลเอ็นต์

ตอนนี้คุณทราบพื้นฐานแล้ว ให้ตรวจสอบขั้นตอนถัดไป และทํางานเพื่อเพิ่มตรรกะตัวจัดการแบบกําหนดเองลงในตัวแทนของคุณ และส่งกลับเหตุการณ์ต่าง ๆ

ขั้นตอนถัดไป

ตามค่าเริ่มต้น Agents Playground จะพร้อมใช้งานหากคุณกําลังใช้ชุดเครื่องมือ Microsoft 365 Agents อยู่แล้ว คุณสามารถใช้หนึ่งในคําแนะนําต่อไปนี้ถ้าคุณต้องการเริ่มต้นใช้งานชุดเครื่องมือ: