---
title: "Build an Enterprise Agent with Semantic Kernel Without API Keys"
description: "Build a helpdesk agent with Semantic Kernel in .NET that uses managed identity, reads Microsoft Graph, and needs approval before escalating tickets."
canonical: "https://adamtheautomator.com/semantic-kernel-enterprise-agent/"
---

# Build an Enterprise Agent with Semantic Kernel Without API Keys

> Build a helpdesk agent with Semantic Kernel in .NET that uses managed identity, reads Microsoft Graph, and needs approval before escalating tickets.

Source: https://adamtheautomator.com/semantic-kernel-enterprise-agent/

---

ATA Learning

Tap to hide

[

ATA Learning

](/)

*   [Home](/)
*   [Tutorials](/tutorials/)
*   [Instructors](/author/)
*   [Advertising](/advertising/)
*   [Recommended Resources](/resources/)
*   [About Adam](/about-adam/)

Search for:  

*   [](https://twitter.com/adbertram)
*   [](https://github.com/Adam-the-Automator)
*   [](https://www.linkedin.com/company/adam-the-automator-llc)
*   [](/feed/)

![Build an Enterprise Agent with Semantic Kernel Without API Keys](https://adamtheautomator.com/wp-content/uploads/publisher/4225d9c85b2b81588979f13aed76ecc2/cff95ac4555f4e5c8a7ff7b89de6f4e32a25cbe24d9ee3b66b3af0dcd6e9e7cd.webp)

# Build an Enterprise Agent with Semantic Kernel Without API Keys

[![](https://secure.gravatar.com/avatar/d0b9d42e21e5622713f8b693aa5c0f9244d5f7dd200ed29b8398f52dee5de337?s=192&d=mm&r=g)Adam Bertram](https://adamtheautomator.com/author/adam-bertram/)1 December 202616 min. read

Categories: [AI Agents](/category/ai-agents/)

Tags:[AI](/tag/ai/)[Microsoft Azure](/tag/microsoft-azure/)[Microsoft Entra](/tag/microsoft-entra/)[Microsoft Graph](/tag/microsoft-graph/)

Table of Contents

*   [How the Agent Plans Without a Planner](#how-the-agent-plans-without-a-planner)
*   [Why Planners Are Gone](#why-planners-are-gone)
*   [Prerequisites](#prerequisites)
*   [Create the Project and Sign In Without a Key](#create-the-project-and-sign-in-without-a-key)
*   [Pick the Credential by Environment](#pick-the-credential-by-environment)
*   [Create the Identity and Grant the Role](#create-the-identity-and-grant-the-role)
*   [Give the Identity Read Access to Microsoft Graph](#give-the-identity-read-access-to-microsoft-graph)
*   [Write the Helpdesk Plugin](#write-the-helpdesk-plugin)
*   [Describe Each Function for the Model](#describe-each-function-for-the-model)
*   [Create the Agent and Let Function Calling Plan](#create-the-agent-and-let-function-calling-plan)
*   [Add an Approval Gate with a Filter](#add-an-approval-gate-with-a-filter)
*   [Stop the Call and Return a Denial](#stop-the-call-and-return-a-denial)
*   [Trace Every Tool Call with OpenTelemetry](#trace-every-tool-call-with-opentelemetry)
*   [Read the Logs Before You Ship](#read-the-logs-before-you-ship)
*   [Run the Agent and Fix What Breaks](#run-the-agent-and-fix-what-breaks)
*   [Test Without Azure](#test-without-azure)
*   [Choose Between Semantic Kernel and Agent Framework](#choose-between-semantic-kernel-and-agent-framework)
*   [Where to Take the Agent Next](#where-to-take-the-agent-next)

Suppose your helpdesk lead asks for an agent that reads a sign-in complaint, checks the employee in [Microsoft Entra ID](https://learn.microsoft.com/en-us/entra/fundamentals/what-is-entra), finds their open tickets, and escalates the stuck one to the on-call engineer. Your security team will also read every line before the agent touches production. What would you hand them?

You’d hand them an agent built on [Microsoft Semantic Kernel](https://learn.microsoft.com/en-us/semantic-kernel/overview/), the open-source .NET SDK for wiring an LLM to your own code. It would reach [Azure OpenAI](https://learn.microsoft.com/en-us/azure/ai-services/openai/overview) through a [managed identity](https://learn.microsoft.com/en-us/entra/identity/managed-identities-azure-resources/overview) instead of an API key and wait for a human’s approval before it changed a ticket. Every tool call it made would also land in a trace.

## How the Agent Plans Without a Planner

The model decides the order in which the agent’s three tools run. Semantic Kernel runs whichever tool the model picks and hands the result back until the model has an answer.

| Tool | Talks to | Changes state? |
| --- | --- | --- |
| `find_user` | [Microsoft Graph](https://learn.microsoft.com/en-us/graph/overview) | No |
| `get_open_tickets` | Your ticketing REST API | No |
| `escalate_ticket` | Your ticketing REST API | Yes |

The diagram below shows where each control sits around those three tools.

![Helpdesk agent architecture](https://adamtheautomator.com/wp-content/uploads/publisher/1794159258907020f70b14a067b87ce1b7b8542b9f74c6a4617d475851bf0faf.jpg)

### Why Planners Are Gone

That loop replaces what older Semantic Kernel articles call a planner. [Microsoft’s page on planners](https://learn.microsoft.com/en-us/semantic-kernel/concepts/planning) says the Stepwise and Handlebars planners “have been deprecated and removed from the Semantic Kernel package.” It points to function calling and a [Stepwise Planner Migration Guide](https://learn.microsoft.com/en-us/semantic-kernel/support/migration/stepwise-planner-migration-guide) instead. With function calling, Semantic Kernel runs the cycle in which the model reads each result and picks the next step. So if a tutorial tells you to import a `HandlebarsPlanner`, it’s out of date.

Microsoft publishes guides for moving Semantic Kernel code to [Microsoft Agent Framework](https://devblogs.microsoft.com/agent-framework/microsoft-agent-framework-version-1-0/), which combines Semantic Kernel’s enterprise foundations with [AutoGen](https://microsoft.github.io/autogen/)’s orchestration. The function-calling loop below carries over even though the types differ.

## Prerequisites

If you want to follow along, you need:

*   The [.NET SDK](https://dotnet.microsoft.com/en-us/download) to build and run the project, confirmed with `dotnet --version` (tested on SDK 10.0.401 with Semantic Kernel 1.82.0).
    
*   The [Azure CLI](https://learn.microsoft.com/en-us/cli/azure/install-azure-cli) signed in with `az login`, to create the identity and role assignments and to give local runs a credential. Tested on 2.90.0.
    
*   An Azure OpenAI resource with a chat deployment that supports function calling, which [requires OpenAI model versions 0613 or newer](https://learn.microsoft.com/en-us/semantic-kernel/concepts/planning). The examples use a deployment named `gpt-4o`, so substitute your own deployment name.
    
*   Permission to grant Microsoft Graph application permissions in your tenant. If you don’t have it, ask your Entra administrator to run the two commands in the Graph section.
    
*   A resource group for the identity (the examples use `rg-helpdesk`) and permission to create role assignments on the Azure OpenAI resource, for example through the [Role Based Access Control Administrator](https://learn.microsoft.com/en-us/azure/role-based-access-control/role-assignments-cli) role.
    
*   A ticketing REST API with `GET tickets` and `POST tickets/{id}/escalate`. The examples use `https://tickets.example.com/api/` as a placeholder, so substitute yours.
    

## Create the Project and Sign In Without a Key

The Learn samples pass an API key to `AddAzureOpenAIChatCompletion`. Your security review will reject a key stored in an environment variable or config file, so this build authenticates with Entra ID instead.

Create the project and add the packages:

```bash
dotnet new console -n HelpdeskAgent
cd HelpdeskAgent
dotnet add package Microsoft.SemanticKernel
dotnet add package Microsoft.SemanticKernel.Agents.Core
dotnet add package Azure.Identity
dotnet add package Microsoft.Graph
dotnet add package OpenTelemetry
dotnet add package OpenTelemetry.Exporter.Console
dotnet add package Microsoft.Extensions.Logging.Console
```

`Microsoft.SemanticKernel.Agents.Core` holds `ChatCompletionAgent`, and version 1.82.0 installs as a stable package, so the command above omits `--prerelease`. `Microsoft.Extensions.Logging.Console` is easy to miss: without it, `AddSimpleConsole` in the next sections fails with compiler error CS1061.

### Pick the Credential by Environment

The [Azure Identity credential chains page](https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication/credential-chains) says: “`DefaultAzureCredential` is undoubtedly the easiest way to get started with the Azure Identity library, but with that convenience comes tradeoffs.” Its advice is to replace it with a specific credential like `ManagedIdentityCredential` once you deploy. The cost shows up when authentication fails, because the chain tries several credentials in sequence and it’s hard to tell which one failed.

Put the credential choice at the start of `Program.cs`, which grows in three places as you build. Every `using` directive goes at the very top of the file, above all other code:

```text
using Azure.Core;
using Azure.Identity;
using Microsoft.Graph;

var isProduction = Environment.GetEnvironmentVariable("DOTNET_ENVIRONMENT") == "Production";
var endpoint = Environment.GetEnvironmentVariable("AZURE_OPENAI_ENDPOINT")!;
var clientId = Environment.GetEnvironmentVariable("AGENT_CLIENT_ID");

TokenCredential credential = isProduction
    ? new ManagedIdentityCredential(ManagedIdentityId.FromUserAssignedClientId(clientId!))
    : new AzureCliCredential();
```

In production the agent uses [a user-assigned managed identity](https://adamtheautomator.com/secure-azure-managed-identities/), an Entra identity that you create once and attach to the host (App Service or Container Apps, for example). On a developer machine it uses the account that ran `az login`, so that account needs the same roles on the Azure OpenAI resource. The same `credential` object goes to both Azure OpenAI and Graph in the next sections.

### Create the Identity and Grant the Role

Create the identity and read its IDs:

```bash
az identity create --name id-helpdesk-agent --resource-group rg-helpdesk
principalId=$(az identity show --name id-helpdesk-agent --resource-group rg-helpdesk --query principalId -o tsv)
clientId=$(az identity show --name id-helpdesk-agent --resource-group rg-helpdesk --query clientId -o tsv)
```

The `principalId` is the identity’s object ID, which role assignments use. The `clientId` is the value to put in `AGENT_CLIENT_ID`, alongside `DOTNET_ENVIRONMENT=Production`, on the host that runs the agent. Now give the identity the least role that can call the model:

```bash
openAiId=$(az cognitiveservices account show --name <openai-resource> --resource-group <openai-rg> --query id -o tsv)
az role assignment create \
  --assignee-object-id $principalId \
  --assignee-principal-type ServicePrincipal \
  --role "Cognitive Services OpenAI User" \
  --scope $openAiId
```

[`--assignee-principal-type ServicePrincipal`](https://learn.microsoft.com/en-us/cli/azure/role/assignment?view=azure-cli-latest#az-role-assignment-create) tells Azure the object ID belongs to an identity, which the CLI reference says avoids “errors caused by propagation latency in Microsoft Graph” right after creation. The scope is the single Azure OpenAI resource. Microsoft’s [role-based access control page for Azure OpenAI](https://learn.microsoft.com/en-us/azure/foundry-classic/openai/how-to/role-based-access-control) lists “Make inference API calls with Microsoft Entra ID” for this role, and it cannot view or copy keys, so [a compromised agent host has no key to leak](https://adamtheautomator.com/secure-azure-openai-deployments-enterprise-2/).

Your own account needs the same role for local runs, because `AzureCliCredential` signs in as you:

```bash
myId=$(az ad signed-in-user show --query id -o tsv)
az role assignment create \
  --assignee-object-id $myId \
  --assignee-principal-type User \
  --role "Cognitive Services OpenAI User" \
  --scope $openAiId
```

* * *

_**Warning: These commands create a managed identity and grant it access to your Azure OpenAI resource. Run them against a non-production resource group first, and delete the role assignment when you finish experimenting.**_

* * *

## Give the Identity Read Access to Microsoft Graph

The `find_user` tool reads employees from Entra ID through Microsoft Graph, and the managed identity needs an application permission to do that. Microsoft’s guide to [assigning a managed identity to an app role](https://learn.microsoft.com/en-us/entra/identity/managed-identities-azure-resources/assign-app-role-managed-identity-azure-cli) explains that the Azure CLI doesn’t expose this directly, so the supported route is `az rest` against Graph.

```bash
graphSpId=$(az ad sp show --id 00000003-0000-0000-c000-000000000000 --query id -o tsv)
roleId=$(az ad sp show --id 00000003-0000-0000-c000-000000000000 --query "appRoles[?value=='User.Read.All'].id | [0]" -o tsv)

az rest -m POST \
  -u "https://graph.microsoft.com/v1.0/servicePrincipals/$principalId/appRoleAssignments" \
  -b "{\"principalId\": \"$principalId\", \"resourceId\": \"$graphSpId\", \"appRoleId\": \"$roleId\"}"
```

The ID `00000003-0000-0000-c000-000000000000` is Microsoft Graph’s application ID, so the first two commands find Graph’s service principal in your tenant and the ID of its `User.Read.All` role. The `az rest` call then assigns that role to your identity. `User.Read.All` is the app-only permission for reading user profiles in the [Microsoft Graph permissions reference](https://learn.microsoft.com/en-us/graph/permissions-reference). Ask for the narrowest permission each tool needs, and add another assignment when you add another Graph call.

* * *

_**Warning: `User.Read.All` lets the identity read the profile of every user in the tenant. Assign it only to an identity that is used by this agent, and review who can run code as that identity.**_

* * *

Role changes don’t take effect instantly. Microsoft’s app-role assignment guide warns that “any changes to the managed identity’s roles can take significant time to process,” because tokens are cached by the underlying infrastructure. If Graph returns 403 right after the assignment, wait and restart the host before changing anything else.

## Write the Helpdesk Plugin

Create a new file named `HelpdeskPlugin.cs` for the plugin, a class whose methods the model can call. [Plugins in Semantic Kernel](https://learn.microsoft.com/en-us/semantic-kernel/concepts/plugins/) notes that plugins “play nicely with dependency injection.” You pass the Graph client and an `HttpClient` through the constructor, the way you would in any other .NET service.

```text
using System.ComponentModel;
using System.Net.Http.Json;
using Microsoft.Graph;
using Microsoft.SemanticKernel;

public sealed class HelpdeskPlugin(GraphServiceClient graph, HttpClient tickets)
{
    [KernelFunction("find_user")]
    [Description("Looks up an employee in Microsoft Entra ID and reports whether the account is enabled.")]
    public async Task<string> FindUserAsync(
        [Description("The employee's user principal name, such as priya.nair@contoso.com")] string user_principal_name)
    {
        var user = await graph.Users[user_principal_name].GetAsync(request =>
            request.QueryParameters.Select = ["displayName", "accountEnabled", "department"]);

        return user is null
            ? "No user found."
            : $"{user.DisplayName} ({user.Department}), account enabled: {user.AccountEnabled}";
    }

    [KernelFunction("get_open_tickets")]
    [Description("Lists the open helpdesk tickets for an employee.")]
    public async Task<string> GetOpenTicketsAsync(
        [Description("The employee's user principal name")] string user_principal_name)
    {
        var url = $"tickets?requester={Uri.EscapeDataString(user_principal_name)}&status=open";
        return await tickets.GetStringAsync(url);
    }

    [KernelFunction("escalate_ticket")]
    [Description("Escalates a ticket to the on-call engineer. Changes ticket state, so a human must approve it.")]
    public async Task<string> EscalateTicketAsync(
        [Description("The ticket number, such as INC-1042")] string ticket_id,
        [Description("One sentence explaining why the ticket needs escalation")] string reason)
    {
        var response = await tickets.PostAsJsonAsync($"tickets/{ticket_id}/escalate", new { reason });
        response.EnsureSuccessStatusCode();
        return $"{ticket_id} escalated.";
    }
}
```

### Describe Each Function for the Model

The model picks tools using only each function’s name, `[Description]` text, and parameters. The plugins page warns that without semantic descriptions “the AI will not correctly call the function,” so treat each description as the contract. The snake\_case names follow the same page’s tip that most LLMs were trained on Python function calling, and the parameter name `user_principal_name` tells the model what to send better than `upn` would.

Two choices in this code keep the model’s context small:

*   `Select` asks Graph for three properties instead of the whole user object.
    
*   Each function returns a short string instead of raw JSON.
    

The plugins page adds that OpenAI recommends no more than 20 tools in a single call and ideally no more than 10, because tool selection gets worse past that range, so register only the plugins a given agent needs.

## Create the Agent and Let Function Calling Plan

Now add the agent code to `Program.cs` below the credential lines, with its `using` directives moved to the top of the file. The code builds a [kernel](https://learn.microsoft.com/en-us/semantic-kernel/concepts/kernel), the dependency injection container that manages the services and plugins your agent uses. It then registers the plugin and wraps both in a `ChatCompletionAgent`, the [Semantic Kernel agent type](https://learn.microsoft.com/en-us/semantic-kernel/frameworks/agent/agent-types/chat-completion-agent) that pairs a model with instructions and tools.

```text
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.Agents;
using Microsoft.SemanticKernel.ChatCompletion;
using Microsoft.SemanticKernel.Connectors.OpenAI;

var builder = Kernel.CreateBuilder();
builder.Services.AddLogging(logging => logging.AddSimpleConsole().SetMinimumLevel(LogLevel.Information));
builder.AddAzureOpenAIChatCompletion("gpt-4o", endpoint, credential);

builder.Services.AddSingleton(new GraphServiceClient(credential));
builder.Services.AddSingleton(new HttpClient { BaseAddress = new Uri("https://tickets.example.com/api/") });
builder.Services.AddSingleton<IAutoFunctionInvocationFilter, ApprovalFilter>();
builder.Plugins.AddFromType<HelpdeskPlugin>("Helpdesk");

Kernel kernel = builder.Build();

ChatCompletionAgent agent = new()
{
    Name = "HelpdeskAgent",
    Instructions = "You are an IT helpdesk agent. Look up the user and their open tickets before acting. Never guess a ticket number.",
    Kernel = kernel,
    Arguments = new KernelArguments(new OpenAIPromptExecutionSettings
    {
        FunctionChoiceBehavior = FunctionChoiceBehavior.Auto()
    })
};

AgentThread thread = new ChatHistoryAgentThread();
while (Console.ReadLine() is { Length: > 0 } input)
{
    await foreach (var response in agent.InvokeAsync(new ChatMessageContent(AuthorRole.User, input), thread))
    {
        Console.WriteLine($"Agent > {response.Message}");
    }
}
```

[`FunctionChoiceBehavior.Auto()`](https://learn.microsoft.com/en-us/semantic-kernel/concepts/ai-services/chat-completion/function-calling/function-choice-behaviors) is the setting that replaces the planner. It lets the model call zero or more registered functions, and Semantic Kernel runs each call and returns the result without your code in between. `AddFromType<HelpdeskPlugin>` builds the plugin through the service provider, which is why the Graph client and `HttpClient` registered above arrive in its constructor. The `ChatHistoryAgentThread` keeps the chat history across turns, so a follow-up like “escalate it” still knows which ticket the previous answer found. The instruction to never guess a ticket number matters because `escalate_ticket` takes the ticket ID as a free-text parameter, and a model that’s short on information will otherwise invent one.

The code references `ApprovalFilter`, which you write next in its own file.

## Add an Approval Gate with a Filter

Of the three tools, only `escalate_ticket` changes state in a system other people depend on, so [it gets a human approver](https://adamtheautomator.com/azure-agent-approval-gate/). The plugins page recommends “human-in-the-loop approval processes” for task automation functions.

Create `ApprovalFilter.cs` with this class, which plugs into Semantic Kernel’s [filters](https://learn.microsoft.com/en-us/semantic-kernel/concepts/enterprise-readiness/filters). The auto function invocation filter runs inside the function-calling loop, once per tool call the model requests, and it can see the function and its arguments before anything executes.

```text
using Microsoft.Extensions.Logging;
using Microsoft.SemanticKernel;

public sealed class ApprovalFilter(ILogger<ApprovalFilter> logger) : IAutoFunctionInvocationFilter
{
    private static readonly HashSet<string> NeedsApproval = ["escalate_ticket"];

    public async Task OnAutoFunctionInvocationAsync(
        AutoFunctionInvocationContext context,
        Func<AutoFunctionInvocationContext, Task> next)
    {
        var name = context.Function.Name;
        var arguments = string.Join(", ", context.Arguments?.Select(a => $"{a.Key}={a.Value}") ?? []);

        if (NeedsApproval.Contains(name) && !Approved($"{name}({arguments})"))
        {
            logger.LogWarning("Denied {Function}({Arguments})", name, arguments);
            context.Result = new FunctionResult(context.Result, "Denied: a human approver rejected this action.");
            return;
        }

        logger.LogInformation("Running {Function}({Arguments})", name, arguments);
        await next(context);
    }

    private static bool Approved(string call)
    {
        Console.Write($"Approve {call}? (y/n) ");
        return Console.ReadLine()?.Trim().ToLowerInvariant() == "y";
    }
}
```

### Stop the Call and Return a Denial

The filters page states, “Without calling `next`, the operation will not be executed.” On a denial the filter sets a result and returns without calling `next`, so the plugin method never runs and your ticketing API never receives the `POST`. The model gets the denial text as the tool result and explains it to the user, which is why the message is plain English. This sample asks on the console. In a real service, replace `Approved` with a message to your approvers (a Teams card or a queue item) and make the filter wait for the answer.

Two gotchas affect this design:

*   `context.Function.Name` is `escalate_ticket`, without the plugin prefix. The model sees the longer `Helpdesk-escalate_ticket`, so a set containing the long name never matches and the gate silently approves everything.
    
*   The set is an opt-in list, so a function added later runs unapproved until someone remembers to add it. For production, invert it: list the read-only functions that may run freely and require approval for every other name.
    

The filters page warns that with dependency injection, “the order of filters is not guaranteed,” so when you add more filters and their order matters, register them with `kernel.AutoFunctionInvocationFilters` instead.

## Trace Every Tool Call with OpenTelemetry

[OpenTelemetry](https://opentelemetry.io/docs/what-is-opentelemetry/) tracing records what the agent did. [Observability in Semantic Kernel](https://learn.microsoft.com/en-us/semantic-kernel/concepts/enterprise-readiness/observability/) says, “Semantic Kernel is designed to be observable. It emits logs, metrics, and traces that are compatible to the OpenTelemetry standard.”

Add these two `using` directives to the top of `Program.cs` with the others, and put the tracer provider just above `var builder`:

```text
using OpenTelemetry;
using OpenTelemetry.Trace;

using var tracerProvider = Sdk.CreateTracerProviderBuilder()
    .AddSource("Microsoft.SemanticKernel*")
    .AddConsoleExporter()
    .Build();
```

Each kernel function execution is recorded as an activity from a source named `Microsoft.SemanticKernel`, and the console exporter prints it as `execute_tool <function name>`. Model-call spans stay off by default. They appear only when you turn on Semantic Kernel’s experimental GenAI diagnostics, either with `AppContext.SetSwitch("Microsoft.SemanticKernel.Experimental.GenAI.EnableOTelDiagnostics", true);` before the kernel is built or with the `SEMANTICKERNEL_EXPERIMENTAL_GENAI_ENABLE_OTEL_DIAGNOSTICS=true` environment variable. Leave the switch off while you run the scripted program in the next section, because its fake completions carry no usage data. The trailing wildcard also catches any source whose name starts with that prefix. `AddConsoleExporter` suits local runs, and in production you swap it for [the exporter your monitoring platform provides](https://adamtheautomator.com/application-insights-catch-failures/) and use the `semantic_kernel.function.invocation.duration` metric to watch tool latency.

### Read the Logs Before You Ship

When you send a triage request, the console prints log lines like these, followed by one trace span per tool call:

```text
info: ApprovalFilter[0]
      Running find_user(user_principal_name=priya.nair@contoso.com)
info: Microsoft.SemanticKernel.KernelFunction[0]
      Function Helpdesk-find_user invoking.
info: Microsoft.SemanticKernel.KernelFunction[0]
      Function Helpdesk-find_user succeeded.
Activity.DisplayName:        execute_tool find_user
--SNIP--
    Name: Microsoft.SemanticKernel
```

The filter above logs every argument at the Information level, and for `find_user` that argument is an employee’s email address. Semantic Kernel itself also logs function arguments and results at the trace level, so decide deliberately whether your own logging should write the same data to a store with wider access.

## Run the Agent and Fix What Breaks

Set the endpoint, sign in, and start the agent:

```bash
export AZURE_OPENAI_ENDPOINT="https://<your-resource>.openai.azure.com/"
az login
dotnet run
```

Type a request like `priya.nair@contoso.com cannot sign in. Triage it.` The agent calls `find_user` and `get_open_tickets`, then asks in chat whether to escalate the ticket. Answer its question with `Yes, escalate INC-1042.` (use the ticket number it reports), and the approval prompt appears before `escalate_ticket` runs. Test each answer in its own session. In the first one, answer `n`, confirm the ticketing API receives no `POST`, and press Enter on an empty line to end the session. After a denial the model refuses to retry in the same session, so start a second `dotnet run`, repeat the same two turns, answer `y`, and confirm the `POST` arrives. The terminal shows that sequence:

![Approval prompt in a run](https://adamtheautomator.com/wp-content/uploads/publisher/fc395f5b0babc65581be6af462c789d32b7a93b540accc74e12fb879293d9635.jpg)

When something goes wrong, start with this table:

| Symptom | Likely cause | Fix |
| --- | --- | --- |
| The model never calls a tool and answers in prose | [Vague `[Description]` text](https://learn.microsoft.com/en-us/semantic-kernel/concepts/ai-services/chat-completion/function-calling/), too many tools, or a model older than version 0613 | Tighten descriptions, register fewer plugins, use a current deployment |
| 401 or 403 from Azure OpenAI | The identity (or your `az login` account locally) lacks `Cognitive Services OpenAI User` on that resource | Repeat the role assignment at the resource scope |
| 403 from Graph right after the grant | Cached tokens | Wait, restart the host, and list assignments with `az rest -m GET` on the same `appRoleAssignments` URL |
| The approval prompt never appears | The set holds `Helpdesk-escalate_ticket` instead of `escalate_ticket` | Use the bare function name in the filter |

### Test Without Azure

You can test the loop without Azure. `AddAzureOpenAIChatCompletion` [accepts an `httpClient` argument](https://learn.microsoft.com/en-us/dotnet/api/microsoft.semantickernel.azureopenaikernelbuilderextensions.addazureopenaichatcompletion?view=semantic-kernel-dotnet), so you can hand it a client whose message handler returns scripted `tool_calls` responses, and give the Graph client and the ticketing `HttpClient` scripted handlers as well. Put this program in a scratch console project that has the same packages plus your `HelpdeskPlugin.cs` and `ApprovalFilter.cs`. It runs the agent twice, answering `y` as the approver the first time and `n` the second:

```text
using System.Net;
using System.Text;
using System.Text.Json;
using Azure.Core;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Graph;
using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.Agents;
using Microsoft.SemanticKernel.ChatCompletion;
using Microsoft.SemanticKernel.Connectors.OpenAI;

var approved = await RunAsync("y");
var denied = await RunAsync("n");

Expect(approved is [var first, var second]
    && first.StartsWith("GET graph.microsoft.com")
    && second.StartsWith("POST tickets.example.com"), "the Graph GET comes before the ticket POST");
Expect(denied is [var only] && only.StartsWith("GET graph.microsoft.com"), "answering n sends no escalation POST");

async Task<List<string>> RunAsync(string approverAnswer)
{
    Console.SetIn(new StringReader(approverAnswer + Environment.NewLine));

    var calls = new List<string>();
    // What the scripted model says, in order: two tool calls, then a final answer.
    var modelReplies = new Queue<string>([
        ToolCall("Helpdesk-find_user", new { user_principal_name = "priya.nair@contoso.com" }),
        ToolCall("Helpdesk-escalate_ticket", new { ticket_id = "INC-1042", reason = "Locked out after failed sign-ins" }),
        Completion("stop", new { role = "assistant", content = "Done." })
    ]);

    var modelClient = new HttpClient(new ScriptedHandler(_ => modelReplies.Dequeue()));
    // Records every Graph and ticketing request; the model client has its own handler.
    var logged = new ScriptedHandler(request =>
    {
        calls.Add($"{request.Method} {request.RequestUri!.Host}{request.RequestUri.AbsolutePath}");
        return request.RequestUri.Host == "graph.microsoft.com"
            ? """{"displayName":"Priya Nair","accountEnabled":true,"department":"Finance"}"""
            : "{}";
    });

    var builder = Kernel.CreateBuilder();
    builder.AddAzureOpenAIChatCompletion("gpt-4o", "https://oai.test",
        DelegatedTokenCredential.Create((_, _) => new AccessToken("fake", DateTimeOffset.UtcNow.AddHours(1))),
        httpClient: modelClient);
    builder.Services.AddLogging();
    builder.Services.AddSingleton(new GraphServiceClient(new HttpClient(logged)));
    builder.Services.AddSingleton(new HttpClient(logged) { BaseAddress = new Uri("https://tickets.example.com/api/") });
    builder.Services.AddSingleton<IAutoFunctionInvocationFilter, ApprovalFilter>();
    builder.Plugins.AddFromType<HelpdeskPlugin>("Helpdesk");

    var agent = new ChatCompletionAgent
    {
        Kernel = builder.Build(),
        Arguments = new KernelArguments(new OpenAIPromptExecutionSettings
        {
            FunctionChoiceBehavior = FunctionChoiceBehavior.Auto()
        })
    };
    await foreach (var _ in agent.InvokeAsync(new ChatMessageContent(AuthorRole.User, "priya.nair@contoso.com cannot sign in. Triage it."))) { }
    return calls;
}

static string Completion(string finishReason, object message) => JsonSerializer.Serialize(new
{
    id = "x", @object = "chat.completion", created = 1, model = "gpt-4o",
    choices = new[] { new { index = 0, finish_reason = finishReason, message } }
});

static string ToolCall(string function, object arguments) => Completion("tool_calls", new
{
    role = "assistant",
    content = (string?)null,
    tool_calls = new[] { new { id = $"call_{function}", type = "function", function = new { name = function, arguments = JsonSerializer.Serialize(arguments) } } }
});

static void Expect(bool condition, string description)
{
    if (!condition) throw new InvalidOperationException($"FAILED: {description}");
    Console.WriteLine($"PASS: {description}");
}

sealed class ScriptedHandler(Func<HttpRequestMessage, string> reply) : HttpMessageHandler
{
    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) =>
        Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)
        {
            Content = new StringContent(reply(request), Encoding.UTF8, "application/json")
        });
}
```

The scripted model asks for `find_user`, then `escalate_ticket`, then gives a final answer. One `logged` handler covers both Graph and the ticketing API, so `calls` holds their requests in arrival order. `DelegatedTokenCredential` hands the Azure client a fake token, and the filter reads its answer from `Console.In`, which the program swaps for each run. The two `Expect` calls check that the Graph `GET` arrives before the ticket `POST`, and that answering `n` records no escalation `POST`. Both print `PASS`.

* * *

_**Reality Check: Scripted handlers test your plugin and filter wiring, while tool selection depends on a live model, so keep a few live runs in your release checklist.**_

* * *

## Choose Between Semantic Kernel and Agent Framework

Everything above is a single agent with a handful of tools, which is the case Semantic Kernel handles well. Microsoft’s [FAQ on Semantic Kernel and Agent Framework](https://devblogs.microsoft.com/agent-framework/semantic-kernel-and-microsoft-agent-framework/) says Microsoft will keep addressing critical bugs and security issues in Semantic Kernel 1.x and will support it for “one year after Microsoft Agent Framework leaves Preview and is Generally Available,” at a minimum. Agent Framework 1.0 shipped for .NET and Python on April 3, 2026 (per the [1.0 announcement](https://devblogs.microsoft.com/agent-framework/microsoft-agent-framework-version-1-0/)), so that minimum runs through at least April 3, 2027. Compare that window with how long this service needs to run before you commit to Semantic Kernel.

Pick the framework by the shape of the design:

*   Stay on Semantic Kernel when your production service runs on it or when you need a single agent with plugins and filters.
    
*   Start on Agent Framework when the design needs [several cooperating agents](https://adamtheautomator.com/build-production-multiagent-ai-systems-azure-ai/) (a triage agent that hands a case to a specialist, for example) or workflows that pause for approval and resume later.
    

The [Agent Framework 1.0 announcement](https://devblogs.microsoft.com/agent-framework/microsoft-agent-framework-version-1-0/) links migration guides for Semantic Kernel and AutoGen users.

## Where to Take the Agent Next

Review the agent against these four controls before you ship:

| Control | What it prevents | Where it lives |
| --- | --- | --- |
| Managed identity with `Cognitive Services OpenAI User` | A leaked API key | `credential` and the role assignment |
| `User.Read.All` on the identity | Broad directory access beyond what the tool needs | The `az rest` assignment |
| `ApprovalFilter` | Unreviewed ticket changes | The auto function invocation filter |
| OpenTelemetry tracing | Tool calls nobody can account for | The tracer provider |

Take these steps next:

1.  Invert the approval set so new functions require approval until you mark them read-only.
    
2.  Send traces to your team’s monitoring platform, and alert on the `semantic_kernel.function.invocation.duration` metric.
    
3.  Add one Microsoft 365 workload at a time, like SharePoint or Teams, with a narrowly scoped permission from the [Graph permissions catalog](https://learn.microsoft.com/en-us/graph/permissions-reference) and its own plugin.
    
4.  Decide whether the agent stays on Semantic Kernel or moves to Agent Framework before you add a second agent, using Microsoft’s migration guides as the checklist.
    

Share this article

[Share on X](https://twitter.com/intent/tweet?url=https%3A%2F%2Fadamtheautomator.com%2Fsemantic-kernel-enterprise-agent%2F&text=Build%20an%20Enterprise%20Agent%20with%20Semantic%20Kernel%20Without%20API%20Keys)[Share on Facebook](https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Fadamtheautomator.com%2Fsemantic-kernel-enterprise-agent%2F)[Share on LinkedIn](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fadamtheautomator.com%2Fsemantic-kernel-enterprise-agent%2F)

## Related Posts

![](https://adamtheautomator.com/wp-content/uploads/publisher/4065d9c85b2b81bf9605cb37d967f788/a9812525518a5125a43d2341858253da973f79467a0eba39ef631295b5a8807b.png)

### [Entra Agent IDs: How to Stop AI Privilege Escalation](/entra-agent-id-privilege-escalation/)

Map the four objects behind a Microsoft Entra Agent ID, follow four documented paths to tenant control, and apply eight controls in risk order.

![](https://adamtheautomator.com/wp-content/uploads/publisher/4065d9c85b2b810f8ec2f16d43234514/30a1ebd88fe7d0a348fc74f3679ed0a07cd493411310d679fd9886586ec027dd.webp)

### [Azure Human Approvals: Stop the Agent Before the Tool Fires](/azure-agent-approval-gate/)

Build a real human approval gate in Microsoft Foundry Agent Service that suspends the run, verifies an Entra ID approver, and logs each decision.

![](https://adamtheautomator.com/wp-content/uploads/publisher/4065d9c85b2b81c2b28df93eee431250/47ab8e33fb2d780dfd7da807ba1617d86ba92a550b57fa1b3c98e4981b0da276.webp)

### [Microsoft Graph API MCP Server: Automate User Provisioning](/microsoft-graph-api-mcp-server-provisioning/)

Build a local Microsoft Graph API MCP server in Python to create disabled test users, assign an approved license, and verify each provisioning step.

## Categories

*   [IT Ops](/category/it-ops/)
*   [Cloud](/category/cloud/)
*   [DevOps](/category/devops/)
*   [Home Ops](/category/home-ops/)
*   [Information Security](/category/infosec/)
*   [Software Development](/category/software-development/)

## Site

*   [Home](/)
*   [Tutorials](/tutorials/)
*   [Instructors](/author/)
*   [Advertising](/advertising/)
*   [Recommended Resources](/resources/)
*   [About Adam](/about-adam/)

Copyright 2026© ATA Learning | [Privacy Policy](/privacy/)
