microsoft/teams.net
Publicmirrored fromhttps://github.com/microsoft/teams.netAvailable
core/samples/A2ABot/Program.cs
56lines · modecode
| 1 | // Copyright (c) Microsoft Corporation. |
| 2 | // Licensed under the MIT License. |
| 3 | |
| 4 | using A2A.AspNetCore; |
| 5 | using A2ABot; |
| 6 | using A2ABot.A2A; |
| 7 | using Microsoft.Teams.Apps; |
| 8 | using Microsoft.Teams.Apps.Handlers; |
| 9 | using AgentCard = A2A.AgentCard; |
| 10 | |
| 11 | WebApplicationBuilder builder = WebApplication.CreateSlimBuilder(args); |
| 12 | builder.Services.AddTeamsBotApplication(); |
| 13 | builder.Services.AddHttpClient("a2a", c => c.Timeout = TimeSpan.FromSeconds(5)); |
| 14 | builder.Services.AddSingleton<A2AClient>(); |
| 15 | builder.Services.AddSingleton<Agent>(); |
| 16 | |
| 17 | Config 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 | |
| 24 | builder.Services.AddSingleton(config); |
| 25 | |
| 26 | AgentCard agentCard = AgentCardFactory.Build(config); |
| 27 | builder.Services.AddA2AAgent<A2AServer>(agentCard); |
| 28 | |
| 29 | WebApplication webApp = builder.Build(); |
| 30 | Agent agent = webApp.Services.GetRequiredService<Agent>(); |
| 31 | TeamsBotApplication teamsApp = webApp.UseTeamsBotApplication(); |
| 32 | |
| 33 | teamsApp.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 | |
| 48 | static 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 | |
| 53 | webApp.MapA2A("/a2a"); |
| 54 | webApp.MapWellKnownAgentCard(agentCard); |
| 55 | |
| 56 | webApp.Run(); |