Introduction
AI agents are transforming how modern applications automate tasks, make decisions, and interact with users. Unlike traditional chatbots that simply respond to prompts, AI agents can plan actions, invoke external tools, and complete multi-step workflows.
Microsoft Semantic Kernel simplifies AI application development in .NET by providing a unified programming model for integrating Large Language Models (LLMs), plugins, memory, and orchestration. In this article, you'll build a simple AI agent using .NET 10 and learn the production practices required to deploy it in real-world applications.
What Are AI Agents?
An AI agent is an application that can:
Understand user requests.
Make decisions based on context.
Execute functions or APIs.
Generate intelligent responses.
Complete tasks autonomously.
Semantic Kernel provides the building blocks for creating these agents without managing complex prompt orchestration manually.
Prerequisites
Before getting started, ensure you have:
.NET 10 SDK (Preview or later)
Visual Studio 2022 or Visual Studio Code
An OpenAI or Azure OpenAI API key
Basic knowledge of C#
Install the required NuGet packages:
dotnet add package Microsoft.SemanticKernel
dotnet add package Microsoft.SemanticKernel.Connectors.OpenAI
Building Your First AI Agent
The following example creates a simple assistant capable of answering developer questions.
using Microsoft.SemanticKernel;
var builder = Kernel.CreateBuilder();
builder.AddOpenAIChatCompletion(
modelId: "gpt-4.1",
apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY"));
var kernel = builder.Build();
var result = await kernel.InvokePromptAsync(
"Explain Dependency Injection in ASP.NET Core in simple terms.");
Console.WriteLine(result);
This example creates a Semantic Kernel instance, connects to an AI model, sends a prompt, and prints the response. While simple, the same pattern scales to production applications where agents can invoke plugins, query databases, or interact with external services.
Production Considerations
Building a working prototype is easy. Building a reliable AI agent requires production-ready practices.
Dependency Injection
Avoid creating a new Kernel instance for every request. Register Semantic Kernel through ASP.NET Core's dependency injection container so it can be reused across your application.
This improves maintainability, simplifies testing, and keeps your AI services centrally configured.
Configuration
Never hardcode API keys or model names.
Store configuration in appsettings.json or environment variables.
{
"OpenAI": {
"Model": "gpt-4.1"
}
}
Keep secrets in Azure Key Vault, Secret Manager, or your preferred secret store instead of source control.
Logging
AI applications can fail due to rate limits, network issues, or invalid prompts.
Use ILogger<T> to record:
Avoid logging sensitive prompts or personal information.
Error Handling
Wrap AI calls inside try-catch blocks to handle transient failures gracefully.
try
{
var response = await kernel.InvokePromptAsync(prompt);
}
catch(Exception ex)
{
logger.LogError(ex, "AI request failed.");
}
For production workloads, implement retry policies with exponential backoff to handle temporary service failures.
Security
Security becomes increasingly important when AI interacts with business data.
Follow these practices:
Store API keys securely.
Validate all user input.
Protect against prompt injection attacks.
Never expose confidential data to the model unnecessarily.
Apply authorization before allowing agents to execute sensitive operations.
Treat AI responses as untrusted output and validate them before performing critical actions.
Performance
AI responses are usually network-bound, making optimization important.
Improve performance by:
Reusing Kernel instances.
Using asynchronous APIs.
Streaming long responses.
Keeping prompts concise.
Caching repeated AI results where appropriate.
Smaller prompts reduce both latency and token costs.
Extending to Multi-Agent Systems
As your application grows, a single agent may become difficult to manage.
Semantic Kernel supports specialized agents, for example:
Research Agent
Coding Agent
Documentation Agent
Review Agent
Each agent focuses on a specific responsibility while collaborating to complete larger workflows. This approach improves maintainability and produces more predictable results.
Deployment
Once your AI agent is working locally, deploying it follows the same process as any ASP.NET Core application.
Popular deployment options include:
Azure App Service
Azure Container Apps
Docker containers
Kubernetes
Use environment-specific configuration and secret management to keep production deployments secure.
Best Practices
Keep prompts focused and specific.
Reuse Kernel instances through dependency injection.
Store secrets outside source code.
Log failures without exposing sensitive information.
Validate AI-generated content before using it.
Monitor latency and token consumption.
Design agents with a single responsibility.
Common Mistakes
Many first-time AI projects suffer from avoidable issues.
Common mistakes include:
Hardcoding API keys.
Creating a new Kernel for every request.
Ignoring exception handling.
Using excessively large prompts.
Trusting AI output without validation.
Logging confidential prompts.
Addressing these issues early results in applications that are easier to maintain and more secure.
Troubleshooting
| Problem | Solution |
|---|
| Authentication failed | Verify your API key and endpoint configuration. |
| Model not found | Ensure the configured model is available for your account. |
| Slow responses | Reduce prompt size, enable streaming, and monitor network latency. |
| Rate limit exceeded | Implement retries with exponential backoff. |
| Unexpected responses | Improve prompt clarity and provide more context. |
Conclusion
Semantic Kernel makes it straightforward for .NET developers to build intelligent AI agents without managing low-level prompt orchestration. While creating a basic agent requires only a few lines of code, production applications demand careful attention to dependency injection, configuration, logging, security, performance, and deployment.
Start with a simple agent, establish a solid production foundation, and then extend your solution with plugins, memory, and multi-agent collaboration as your application's requirements evolve.