Condividi tramite


Avvio rapido: creare e testare un agente di base

Questa guida introduttiva illustra la creazione di un agente del motore personalizzato che risponde con qualsiasi messaggio inviato.

Prerequisiti

  • Python 3.9 o versione successiva.

    • Per installare Python, passare a https://www.python.org/downloads/e seguire le istruzioni per il sistema operativo.
    • Per verificare la versione, in una finestra del terminale digitare python --version.
  • Editor di codice di propria scelta. Queste istruzioni usano Visual Studio Code.

    Se si usa Visual Studio Code, installare l'estensione Python

Inizializzare il progetto e installare l'SDK

Creare un progetto Python e installare le dipendenze necessarie.

  1. Aprire un terminale e creare una nuova cartella

    mkdir echo
    cd echo
    
  2. Aprire la cartella usando Visual Studio Code usando questo comando:

    code .
    
  3. Creare un ambiente virtuale con il metodo scelto e attivarlo tramite Visual Studio Code o in un terminale.

    Quando si usa Visual Studio Code, è possibile usare questi passaggi con l'estensione Python installata.

    1. Premere F1, digitare Python: Create environmente premere INVIO.

      1. Selezionare Venv per creare un .venv ambiente virtuale nell'area di lavoro corrente.

      2. Selezionare un'installazione python per creare l'ambiente virtuale.

        Il valore potrebbe essere simile al seguente:

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

  4. Installa l'SDK degli Agenti

    Usare pip per installare il pacchetto microsoft-agents-hosting-aiohttp con questo comando:

    pip install microsoft-agents-hosting-aiohttp
    

Creare l'applicazione server e importare le librerie necessarie

  1. Creare un file denominato start_server.py, copiare il codice seguente e incollarlo in:

    # 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
    

    Questo codice definisce una start_server funzione che verrà usata nel file successivo.

  2. Nella stessa directory creare un file denominato app.py con il codice seguente.

    # 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
    

Creare un'istanza dell'agente come AgentApplication

In app.py aggiungere il codice seguente per creare AGENT_APP come istanza di AgentApplication e implementare tre route per rispondere a tre eventi:

  • Aggiornamento conversazione
  • messaggio /help
  • qualsiasi altra attività
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}")

Avviare il server Web per l'ascolto in localhost:3978

Alla fine di app.pyavviare il server Web usando start_server.

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

Esegui l'agente in locale in modalità anonima

Dal terminale eseguire questo comando:

python app.py

Il terminale deve restituire quanto segue:

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

Testare l'agente localmente

  1. Da un altro terminale (per mantenere l'agente in esecuzione) installare Microsoft 365 Agents Playground con questo comando:

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

    Annotazioni

    Questo comando usa npm perché Microsoft 365 Agents Playground non è disponibile tramite pip.

    Il terminale dovrebbe restituire un risultato simile al seguente:

    added 1 package, and audited 130 packages in 1s
    
    19 packages are looking for funding
    run `npm fund` for details
    
    found 0 vulnerabilities
    
  2. Eseguire lo strumento di test per interagire con l'agente usando questo comando:

    teamsapptester
    

    Il terminale dovrebbe restituire un risultato simile al seguente:

    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\"}"}}
    

Il teamsapptester comando apre il browser predefinito e si connette all'agente.

Il tuo agente nell'ambiente degli agenti

È ora possibile inviare qualsiasi messaggio per visualizzare la risposta echo o inviare il messaggio /help per vedere come viene instradato il messaggio al _help gestore.

Questa guida introduttiva illustra la creazione di un agente del motore personalizzato che risponde con qualsiasi messaggio inviato.

Prerequisiti

  • Node.js v22 o versione successiva

    • Per installare Node.js passare a nodejs.org e seguire le istruzioni per il sistema operativo.
    • Per verificare la versione, in una finestra del terminale digitare node --version.
  • Editor di codice di propria scelta. Queste istruzioni usano Visual Studio Code.

Inizializzare il progetto e installare l'SDK

Usare npm per inizializzare un progetto node.js creando un package.json e installando le dipendenze necessarie

  1. Aprire un terminale e creare una nuova cartella

    mkdir echo
    cd echo
    
  2. Inizializzare il progetto di node.js

    npm init -y
    
  3. Installa l'SDK degli Agenti

    npm install @microsoft/agents-hosting-express
    
  4. Aprire la cartella usando Visual Studio Code usando il comando seguente:

    code .
    

Importare le librerie necessarie

Creare il file index.mjs e importare i pacchetti NPM seguenti nel codice dell'applicazione:

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

Implementare EchoAgent come AgentApplication

In index.mjsaggiungere il codice seguente per creare l'estensione EchoAgentdi AgentApplication e implementare tre route per rispondere a tre eventi:

  • Aggiornamento conversazione
  • messaggio /help
  • qualsiasi altra attività
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)
  }
}

Avviare il server Web per l'ascolto in localhost:3978

Alla fine di index.mjs, avvia il server web utilizzando startServer basato su Express, usando MemoryStorage come sistema di archiviazione dello stato del turno.

startServer(new EchoAgent(new MemoryStorage()))

Eseguire in locale l'agente in modalità anonima

Dal terminale eseguire questo comando:

node index.mjs

Il terminale deve restituire quanto segue:

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

Testare l'agente localmente

  1. Da un altro terminale (per mantenere l'agente in esecuzione) installare Microsoft 365 Agents Playground con questo comando:

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

    Il terminale dovrebbe restituire un risultato simile al seguente:

    added 1 package, and audited 130 packages in 1s
    
    19 packages are looking for funding
    run `npm fund` for details
    
    found 0 vulnerabilities
    
  2. Eseguire lo strumento di test per interagire con l'agente usando questo comando:

    node_modules/.bin/teamsapptester
    

    Il terminale dovrebbe restituire un risultato simile al seguente:

    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\"}"}}
    

Il teamsapptester comando apre il browser predefinito e si connette all'agente.

Il tuo agente nell'ambiente degli agenti

È ora possibile inviare qualsiasi messaggio per visualizzare la risposta echo o inviare il messaggio /help per vedere come viene instradato il messaggio al _help gestore.

Questa guida introduttiva illustra la creazione di un agente del motore personalizzato che risponde con qualsiasi messaggio inviato.

Prerequisiti

  • .NET 8.0 SDK o versione successiva

    • Per installare .NET SDK, passare a dotnet.microsoft.com e seguire le istruzioni per il sistema operativo.
    • Per verificare la versione, in una finestra del terminale digitare dotnet --version.
  • Editor di codice di propria scelta. Queste istruzioni usano Visual Studio Code.

Inizializzare il progetto e installare l'SDK

Usare dotnet per creare un nuovo progetto Web e installare le dipendenze necessarie.

  1. Aprire un terminale e creare una nuova cartella

    mkdir echo
    cd echo
    
  2. Inizializzare il progetto .NET

    dotnet new web
    
  3. Installa l'SDK degli Agenti

    dotnet add package Microsoft.Agents.Hosting.AspNetCore
    
  4. Aprire la cartella usando Visual Studio Code usando questo comando:

    code .
    

Importare le librerie necessarie

In Program.cssostituire il contenuto esistente e aggiungere le istruzioni seguenti using per importare i pacchetti SDK nel codice dell'applicazione:

// 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;

Implementare EchoAgent come AgentApplication

In Program.cs, dopo le using istruzioni aggiungere il codice seguente per creare l'estensione EchoAgentAgentApplication e implementare route per rispondere agli eventi:

  • Aggiornamento conversazione
  • Qualsiasi altra attività
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);
   }
}

Configurare il server Web e registrare l'applicazione agente

In Program.cs, dopo le using istruzioni aggiungere il codice seguente per configurare l'host Web, registrare l'agente ed eseguire il mapping dell'endpoint /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();

Impostare il server Web per ascoltare su localhost:3978

In launchSettings.json aggiornare applicationURL a http://localhost:3978 in modo che l'app sia in ascolto sulla porta appropriata.

Eseguire l'agente in locale in modalità anonima

Dal terminale eseguire questo comando:

dotnet run

Il terminale dovrebbe restituire un risultato simile al seguente:

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

Testare l'agente localmente

  1. Da un altro terminale (per mantenere l'agente in esecuzione) installare Microsoft 365 Agents Playground con il comando seguente:

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

    Annotazioni

    Questo comando usa npm perché Microsoft 365 Agents Playground è distribuito come pacchetto npm.

    Il terminale dovrebbe restituire un risultato simile al seguente:

    added 1 package, and audited 130 packages in 1s
    
    19 packages are looking for funding
    run `npm fund` for details
    
    found 0 vulnerabilities
    
  2. Eseguire lo strumento di test per interagire con l'agente usando questo comando:

    teamsapptester
    

    Il terminale dovrebbe restituire un risultato simile al seguente:

    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\"}"}}
    

Il teamsapptester comando apre il browser predefinito e si connette all'agente.

Il tuo agente nell'ambiente degli agenti

Nell'input di testo immettere e inviare qualsiasi messaggio per visualizzare la risposta echo.

Passaggi successivi

Agents Playground è disponibile per impostazione predefinita se si usa già Microsoft 365 Agents Toolkit. Se si vuole iniziare a usare il toolkit, è possibile usare una delle guide seguenti: