microsoft/teams.net

Public

mirrored fromhttps://github.com/microsoft/teams.netAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
kavin/agents-sdk-interop

Branches

Tags

  • No tags available.
0Branches0Tags
Go to file
Add file
Code

Clone

HTTPS

Download ZIP

core/samples/A2ABot/Program.cs

56lines · modecode

1// Copyright (c) Microsoft Corporation.
2// Licensed under the MIT License.
3
4using A2A.AspNetCore;
5using A2ABot;
6using A2ABot.A2A;
7using Microsoft.Teams.Apps;
8using Microsoft.Teams.Apps.Handlers;
9using AgentCard = A2A.AgentCard;
10
11WebApplicationBuilder builder = WebApplication.CreateSlimBuilder(args);
12builder.Services.AddTeamsBotApplication();
13builder.Services.AddHttpClient("a2a", c => c.Timeout = TimeSpan.FromSeconds(5));
14builder.Services.AddSingleton<A2AClient>();
15builder.Services.AddSingleton<Agent>();
16
17Config config = new(
18 Name: builder.Configuration["Bot:Name"] ?? throw new InvalidOperationException("Bot:Name is required."),
19 SelfUrl: builder.Configuration["Bot:SelfUrl"] ?? throw new InvalidOperationException("Bot:SelfUrl is required."),
20 Description: builder.Configuration["Bot:Description"] ?? throw new InvalidOperationException("Bot:Description is required."),
21 PeerUrl: builder.Configuration["Bot:PeerUrl"] ?? throw new InvalidOperationException("Bot:PeerUrl is required."),
22 PeerName: builder.Configuration["Bot:PeerName"] ?? throw new InvalidOperationException("Bot:PeerName is required."));
23
24builder.Services.AddSingleton(config);
25
26AgentCard agentCard = AgentCardFactory.Build(config);
27builder.Services.AddA2AAgent<A2AServer>(agentCard);
28
29WebApplication webApp = builder.Build();
30Agent agent = webApp.Services.GetRequiredService<Agent>();
31TeamsBotApplication teamsApp = webApp.UseTeamsBotApplication();
32
33teamsApp.OnMessage(async (context, ct) =>
34{
35 string text = context.Activity.Text?.Trim() ?? string.Empty;
36 string convId = context.Activity.Conversation!.Id!;
37 TurnIdentity identity = new(
38 AadObjectId: Required(context.Activity.From?.AadObjectId, "From.AadObjectId"),
39 UserName: context.Activity.From?.Name ?? "User",
40 TenantId: Required(context.Activity.Conversation?.TenantId, "Conversation.TenantId"),
41 ServiceUrl: Required(context.Activity.ServiceUrl?.ToString(), "ServiceUrl"));
42
43 string reply = await agent.RunAsync(convId, identity, text, ct);
44 if (!string.IsNullOrWhiteSpace(reply))
45 await context.SendActivityAsync(reply, ct);
46});
47
48static string Required(string? value, string field) =>
49 string.IsNullOrWhiteSpace(value)
50 ? throw new InvalidOperationException($"Activity is missing required field for handoff: {field}.")
51 : value;
52
53webApp.MapA2A("/a2a");
54webApp.MapWellKnownAgentCard(agentCard);
55
56webApp.Run();