Introduction

AI agents are rapidly becoming a core architectural component of modern enterprise applications. Unlike traditional chatbots that simply respond to prompts, AI agents can reason, plan, invoke tools, access enterprise data, execute workflows, and make context-aware decisions.

With the combination of .NET 9, Azure OpenAI, Semantic Kernel, Azure AI Search, and function-calling capabilities, developers can build sophisticated AI agents that automate business processes and enhance user experiences.

This guide explores the architecture, implementation, and best practices for building production-ready AI agents using .NET 9 and Azure OpenAI.

What is an AI Agent?

An AI Agent is an autonomous software system that can:

  • Understand user goals

  • Maintain conversational context

  • Reason about tasks

  • Execute actions

  • Interact with external systems

  • Utilize tools and APIs

  • Generate intelligent responses

Unlike simple LLM-based applications, agents actively perform tasks rather than only generating text.

Examples include:

  • Customer support agents

  • Enterprise knowledge assistants

  • Sales automation agents

  • Workflow orchestration agents

  • IT support copilots

  • Document processing agents

AI Agent Architecture

A modern AI Agent typically consists of:

Code
User
 │
 ▼
Frontend
 │
 ▼
.NET 9 API
 │
 ├── Azure OpenAI
 │
 ├── Semantic Kernel
 │
 ├── Azure AI Search
 │
 ├── Business APIs
 │
 ├── SQL Database
 │
 └── External Tools

Core components:

Azure OpenAI

Provides:

  • GPT-4o

  • GPT-4.1

  • Embedding models

  • Function Calling

  • Structured Outputs

Semantic Kernel

Microsoft's orchestration framework for:

  • Agent workflows

  • Memory management

  • Plugins

  • Planning

  • Tool invocation

Provides:

  • Retrieval-Augmented Generation (RAG)

  • Enterprise knowledge retrieval

  • Vector search

  • Hybrid search

.NET 9

Provides:

  • High-performance APIs

  • Native cloud integration

  • Dependency injection

  • Async programming

  • Minimal APIs

Prerequisites

Before starting:

Software Requirements

Code
.NET 9 SDK
Visual Studio 2026
Azure Subscription
Azure OpenAI Service
Azure AI Search
SQL Server

Verify installation:

Bash
dotnet --version

Expected output:

Bash
9.0.x

Creating the Project

Create a new Web API:

Bash
dotnet new webapi -n AiAgentDemo

Navigate into project:

Bash
cd AiAgentDemo

Add required packages:

Bash
dotnet add package Microsoft.SemanticKernel

dotnet add package Azure.AI.OpenAI

dotnet add package Azure.Search.Documents

dotnet add package Microsoft.Extensions.AI

Configuring Azure OpenAI

Add settings in appsettings.json:

JSON
{
  "AzureOpenAI": {
    "Endpoint": "https://your-openai.openai.azure.com/",
    "ApiKey": "YOUR_KEY",
    "DeploymentName": "gpt-4o"
  }
}

Create configuration model:

C#
public class AzureOpenAiOptions
{
    public string Endpoint { get; set; }
    public string ApiKey { get; set; }
    public string DeploymentName { get; set; }
}

Register service:

C#
builder.Services.Configure<AzureOpenAiOptions>(
    builder.Configuration.GetSection("AzureOpenAI"));

Creating Azure OpenAI Client

C#
using Azure;
using Azure.AI.OpenAI;

var client = new AzureOpenAIClient(
    new Uri(endpoint),
    new AzureKeyCredential(apiKey));

Initialize chat client:

C#
var chatClient =
    client.GetChatClient(deploymentName);

Implementing Semantic Kernel

Create kernel:

C#
var builder = Kernel.CreateBuilder();

builder.AddAzureOpenAIChatCompletion(
    deploymentName,
    endpoint,
    apiKey);

Kernel kernel = builder.Build();

Semantic Kernel acts as the orchestration engine for the AI agent.

Also Read : Using Semantic Kernel with .NET for AI Agent Development

Building Agent Memory

Agents require memory to maintain context.

Create conversation history:

C#
ChatHistory history = new();

history.AddSystemMessage(
    "You are an enterprise AI assistant.");

Add user message:

C#
history.AddUserMessage(
    "Generate monthly sales summary.");

This enables multi-turn conversations.

Creating Agent Plugins

Plugins allow agents to interact with business systems.

Example:

C#
public class WeatherPlugin
{
    [KernelFunction]
    public string GetWeather(string city)
    {
        return $"Weather in {city} is sunny.";
    }
}

Register plugin:

C#
kernel.ImportPluginFromType<WeatherPlugin>();

Now the agent can invoke the plugin automatically.

Also Read : How to Integrate Claude AI with .NET Applications

Function Calling

One of the most important capabilities of modern AI agents is function calling.

Example:

C#
OpenAIPromptExecutionSettings settings =
    new()
    {
        ToolCallBehavior =
        ToolCallBehavior.AutoInvokeKernelFunctions
    };

Invoke prompt:

C#
var result =
await kernel.InvokePromptAsync(
    "What's the weather in New York?",
    new(settings));

The model automatically decides when to call the plugin.

Adding Retrieval-Augmented Generation (RAG)

Enterprise AI agents require access to company knowledge.

Azure AI Search provides:

  • Vector search

  • Semantic ranking

  • Hybrid search

Create search client:

C#
SearchClient searchClient =
    new SearchClient(
        endpoint,
        indexName,
        credential);

Perform search:

C#
var results =
await searchClient.SearchAsync<SearchDocument>(
    query);

Inject retrieved documents into prompt:

C#
var prompt = $@"
Answer using the following context:

{documents}

Question:
{question}";

This improves accuracy and reduces hallucinations.

Building Agent Planning

Modern agents can break complex goals into tasks.

Example:

User asks:

Code
Create sales report and email management.

Agent plan:

Code
1. Retrieve sales data
2. Generate summary
3. Format report
4. Send email

Semantic Kernel planners can automate this decomposition process.

Creating Minimal API Endpoint

Example endpoint:

C#
app.MapPost("/chat",
async (
    ChatRequest request,
    Kernel kernel) =>
{
    var response =
    await kernel.InvokePromptAsync(
        request.Message);

    return Results.Ok(
        response.ToString());
});

Request:

JSON
{
  "message":
  "Generate quarterly sales report"
}

Response:

JSON
{
  "result":
  "Quarterly sales increased by 18%..."
}

Multi-Agent Architecture

Enterprise applications increasingly use multiple specialized agents.

Example:

Code
Supervisor Agent
      │
 ┌────┼────┐
 ▼    ▼    ▼
Sales HR Finance
Agent Agent Agent

Benefits:

  • Better specialization

  • Improved scalability

  • Reduced prompt complexity

  • Better governance

Each agent owns a specific domain.

Security Considerations

Production AI agents must implement:

Authentication

C#
builder.Services
.AddAuthentication();

Authorization

C#
[Authorize]
public class AgentController
{
}

Prompt Injection Protection

Validate:

  • User inputs

  • Retrieved documents

  • Tool outputs

Never allow unrestricted tool execution.

Data Protection

Use:

  • Azure Key Vault

  • Managed Identity

  • Encrypted storage

Monitoring and Observability

Monitor:

  • Token consumption

  • Latency

  • Tool usage

  • Error rates

  • User feedback

Integrate:

Code
Azure Monitor
Application Insights
Log Analytics

Track:

Code
Prompt Cost
Completion Cost
Agent Success Rate
Hallucination Rate

Performance Optimization

Use Streaming Responses

C#
await foreach(
var update in chatClient.CompleteChatStreamingAsync())
{
}

Benefits:

  • Faster perceived response times

  • Better user experience

Cache Embeddings

Avoid generating duplicate embeddings.

Optimize Context Windows

Only retrieve relevant documents.

Use Smaller Models

Not every task requires GPT-4o.

Use lightweight models where appropriate.

Enterprise Use Cases

Customer Support Agent

Capabilities:

  • Answer support questions

  • Create tickets

  • Retrieve account information

HR Copilot

Capabilities:

  • Leave management

  • Policy retrieval

  • Employee onboarding

Sales Assistant

Capabilities:

  • Lead qualification

  • Opportunity analysis

  • CRM integration

IT Helpdesk Agent

Capabilities:

  • Password reset workflows

  • Knowledge retrieval

  • Incident management

Best Practices

Keep Prompts Structured

Define:

Code
Role
Objective
Constraints
Expected Output

Use RAG

Avoid relying solely on model knowledge.

Design Domain-Specific Agents

Specialized agents outperform general-purpose agents.

Implement Human Approval

For critical actions:

Code
Payments
Approvals
Customer Communication

Monitor Continuously

Agent quality must be measured and improved.

Conclusion

.NET 9 and Azure OpenAI provide a powerful foundation for building enterprise-grade AI agents. By combining Azure OpenAI, Semantic Kernel, Azure AI Search, function calling, memory management, and modern cloud-native architecture, organizations can create intelligent systems capable of reasoning, retrieving information, invoking tools, and automating complex workflows.

As AI agents continue evolving from conversational assistants into autonomous digital workers, .NET developers are uniquely positioned to build secure, scalable, and production-ready agentic applications that transform enterprise operations.