Files
agent-framework/dotnet/samples/HelloHttpApi/HelloHttpApi.ApiService/HostApplicationBuilderAgentExtensions.cs
T
Aditya Mandaleeka f5b35d8403 .NET: CosmosDB Actor State Storage (#262)
* Implement CosmosDB actor state storage.

* Fix.

* Minor fixes.

* Fixes.

* Make CosmosDB initialization be lazy.

* Remove unnecessary read from write path.

* Throw on empty writes.

* Add arg validation for read.

* Add CosmosIdSanitizer.

* Fix.

* Fix.

* Simplify doc IDs.

* Update comment.

* fb

* Make LazyCosmosContainer internal and add tests.

* Make test constants public and remove IVT.

* Use source generated JSON context for future nativeAOT support.

* Re-add dropped comments.
2025-08-05 00:11:49 +00:00

46 lines
2.1 KiB
C#

// Copyright (c) Microsoft. All rights reserved.
using Microsoft.Agents.Orchestration;
using Microsoft.Extensions.AI;
using Microsoft.Extensions.AI.Agents;
using Microsoft.Extensions.AI.Agents.Runtime;
using Microsoft.Extensions.AI.Agents.Runtime.Storage.CosmosDB;
namespace HelloHttpApi.ApiService;
public static class HostApplicationBuilderAgentExtensions
{
public static IHostApplicationBuilder AddAIAgent(this IHostApplicationBuilder builder, string name, string instructions, string? chatClientKey = null)
{
var agentKey = $"agent:{name}";
builder.Services.AddKeyedSingleton<AIAgent>(agentKey, (sp, key) =>
{
var chatClient = chatClientKey is null ? sp.GetRequiredService<IChatClient>() : sp.GetRequiredKeyedService<IChatClient>(chatClientKey);
ChatClientAgent triage = new(chatClient, "You are a triage agent. You will determine which agent to hand off the conversation to based on the user's input.", $"{name}_triageAgent");
ChatClientAgent target = new(chatClient, instructions, $"{name}_targetAgent");
ChatClientAgent customerService = new(chatClient, "You are a customer service agent. You will handle rude, angry, or upset customer inquiries, asking them to be more calm and polite.", $"{name}_customerServiceAgent");
return Handoffs
.StartWith(triage)
.Add(triage, target, "Hand off to the target agent for handling normal customer requests.")
.Add(triage, customerService, "Hand off to the customer service agent for handling rude customer inquiries.")
.Build("PirateWorkflow");
});
var actorBuilder = builder.AddActorRuntime();
// Add CosmosDB state storage to override default storage
builder.Services.AddCosmosActorStateStorage("actor-state-db", "ActorState");
actorBuilder.AddActorType(
new ActorType(agentKey),
(sp, ctx) => new ChatClientAgentActor(
sp.GetRequiredKeyedService<AIAgent>(agentKey),
ctx,
sp.GetRequiredService<ILogger<ChatClientAgentActor>>()));
return builder;
}
}