התחלה מהירה: יצירת ובדיקת סוכן בסיסי

ההפעלה המהירה הזו מנחה אותך ביצירת סוכן מנוע מותאם אישית שמגיב עם כל הודעה שתשלח אליו.

‏‫דרישות מוקדמות‬

  • 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 באמצעות הפקודה הבאה:

    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
    

יצירת מופע של הסוכן מסוג 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

הפעלת הסוכן באופן מקומי במצב אנונימי

בטרמינל שלכם, הריצו את הפקודה הבאה:

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
    

    הערה

    פקודה זו משתמשת ב-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 פותחת את דפדפן ברירת המחדל שלכם ומתחברת לסוכן.

הסוכן שלך במגרש המשחקים של הסוכנים

עכשיו אפשר לשלוח כל הודעה כדי לראות את תשובת ה-echo, או לשלוח את ההודעה /help כדי לראות איך ההודעה הזו מנותבת למטפל _help .

ההפעלה המהירה הזו מנחה אותך ביצירת סוכן מנוע מותאם אישית שמגיב עם כל הודעה שתשלח אליו.

‏‫דרישות מוקדמות‬

  • 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 כ-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 ההפעלה שרת האינטרנט משתמש ב-startServer בהתבסס על אקספרס ומשתמש ב-MemoryStorage כאחסון מצב תור.

startServer(new EchoAgent(new MemoryStorage()))

הפעלת הסוכן באופן מקומי במצב אנונימי

בטרמינל שלכם, הריצו את הפקודה הבאה:

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 פותחת את דפדפן ברירת המחדל שלכם ומתחברת לסוכן.

הסוכן שלך במגרש המשחקים של הסוכנים

עכשיו אפשר לשלוח כל הודעה כדי לראות את תשובת ה-echo, או לשלוח את ההודעה /help כדי לראות איך ההודעה הזו מנותבת למטפל _help .

ההפעלה המהירה הזו מנחה אותך ביצירת סוכן מנוע מותאם אישית שמגיב עם כל הודעה שתשלח אליו.

‏‫דרישות מוקדמות‬

  • .NET 8.0 SDK או מעלה

    • כדי להתקין את ה-.NET SDK, עבור ל-dotnet.microsoft.com ופעלו לפי ההוראות של מערכת ההפעלה שלך.
    • כדי לאמת את הגירסה, בחרו חלון טרמינל והקלידו dotnet --version.
  • עורך קוד לבחירתך. הוראות אלו משתמשות בVisual Studio Code.

אתחל את הפרויקט והתקן את ה-SDK

השתמשו ב-dotnet כדי ליצור פרויקט Web חדש ולהתקין את התלויות הנדרשות.

  1. פתיחת טרמינל וצור תיקייה חדשה

    mkdir echo
    cd echo
    
  2. אתחול פרויקט .NET

    dotnet new web
    
  3. התקנת Agents SDK

    dotnet add package Microsoft.Agents.Hosting.AspNetCore
    
  4. פתחו את התיקייה באמצעות Visual Studio Code באמצעות הפקודה הבאה:

    code .
    

ייבוא הספריות הנדרשות

ב Program.cs-, החלף את התוכן הקיים והוסף את הפקודות הבאות using לייבוא חבילות ה-SDK לקוד היישום שלך:

// 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, הוסיפו את הקוד הבא כדי ליצור את ה-EchoAgent שמרחיב את AgentApplication, וממשו מסלולים שיגיבו לאירועים:

  • עדכון שיחה
  • כל פעילות אחרת
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);
   }
}

הגדרת שרת האינטרנט ורשום את יישום הסוכן

ב- Program.cs, לאחר הפקודות using, הוסף את הקוד הבא להגדרת שרת האינטרנט, רישום הסוכן ומיפוי נקודת הקצה /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();

הגדרת שרת האינטרנט להאזנה ב-localhost‏:3978

ב-launchSettings.json, עדכן את applicationURL ל-http://localhost:3978 כך שהאפליקציה תאזין לפורט הנכון.

הפעלת הסוכן באופן מקומי במצב אנונימי

בטרמינל שלכם, הריצו את הפקודה הבאה:

dotnet run

הטרמינל אמור להחזיר משהו כמו:

info: Microsoft.Hosting.Lifetime[14]
      Now listening on: http://localhost:3978

בדיקת הסוכן באופן מקומי

  1. בטרמינל נוסף (כדי לשמור על הסוכן פועל), התקינו את Microsoft‏ 365 Agents Playground עם הפקודה הבאה:

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

    הערה

    פקודה זו משתמשת ב-npm מכיוון ש-Microsoft 365 Agents Playground מופץ כחבילת npm.

    הטרמינל אמור להחזיר משהו כמו:

    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 זמין כברירת מחדל אם אתם כבר משתמשים ב-Microsoft‏ 365 Agents Toolkit. ניתן להיעזר באחד מהמדריכים הבאים כדי להתחיל לעבוד עם ערכת הכלים: