semantic-kernel
This Claude Code skill enables building AI-driven .NET applications using Microsoft's Semantic Kernel framework. It provides guidance for constructing kernels, registering services, creating plugins with function-calling patterns, and implementing AI orchestration. Use it when adding LLM-powered prompts or plugins to .NET applications, reviewing kernel setup, or migrating to current Semantic Kernel APIs.
git clone --depth 1 https://github.com/managedcode/dotnet-skills /tmp/semantic-kernel && cp -r /tmp/semantic-kernel/catalog/Frameworks/Semantic-Kernel/skills/semantic-kernel ~/.claude/skills/semantic-kernelSKILL.md
# Semantic Kernel for .NET
## Trigger On
- adding AI-driven prompts, plugins, or orchestration to a .NET app
- reviewing kernel construction, service registration, or plugin usage
- building function-calling patterns with LLMs
- migrating older Semantic Kernel code to current APIs
## Documentation
- [Semantic Kernel Overview](https://learn.microsoft.com/en-us/semantic-kernel/overview/)
- [Plugins and Functions](https://learn.microsoft.com/en-us/semantic-kernel/concepts/plugins/)
- [Agent Functions](https://learn.microsoft.com/en-us/semantic-kernel/frameworks/agent/agent-functions)
- [GitHub Repository](https://github.com/microsoft/semantic-kernel)
- [Microsoft Agent Framework](https://learn.microsoft.com/en-us/semantic-kernel/frameworks/agent/)
### References
- [patterns.md](references/patterns.md) - Plugin patterns, function calling patterns, multi-agent patterns, prompt templates, and RAG patterns
- [anti-patterns.md](references/anti-patterns.md) - Common Semantic Kernel mistakes and how to avoid them
## Core Concepts
| Concept | Description |
|---------|-------------|
| **Kernel** | Central orchestrator for AI services and plugins |
| **Plugin** | Collection of functions exposed to the LLM |
| **Function** | Native C# method or prompt template |
| **Chat Completion** | LLM service for generating responses |
| **Memory** | Vector storage for semantic search |
## Workflow
1. **Build the Kernel** with required services
2. **Create Plugins** with well-described functions
3. **Configure Function Calling** for automatic tool use
4. **Handle Responses** and manage conversation state
5. **Test and Observe** AI behavior with logging
## Kernel Setup
### Basic Configuration
```csharp
var builder = Kernel.CreateBuilder();
builder.AddAzureOpenAIChatCompletion(
deploymentName: "gpt-4",
endpoint: config["AzureOpenAI:Endpoint"]!,
apiKey: config["AzureOpenAI:ApiKey"]!);
// Or OpenAI
builder.AddOpenAIChatCompletion(
modelId: "gpt-4",
apiKey: config["OpenAI:ApiKey"]!);
var kernel = builder.Build();
```
### With Dependency Injection
```csharp
builder.Services.AddKernel()
.AddAzureOpenAIChatCompletion(
deploymentName: "gpt-4",
endpoint: config["AzureOpenAI:Endpoint"]!,
apiKey: config["AzureOpenAI:ApiKey"]!);
// Register plugins
builder.Services.AddSingleton<WeatherPlugin>();
builder.Services.AddSingleton<OrderPlugin>();
// In your service
public class AiService(Kernel kernel)
{
public async Task<string> ChatAsync(string message)
{
var response = await kernel.InvokePromptAsync(message);
return response.ToString();
}
}
```
## Plugin Patterns
### Creating a Plugin
```csharp
public class WeatherPlugin
{
[KernelFunction]
[Description("Gets the current weather for a specified city")]
public async Task<string> GetWeather(
[Description("The city name, e.g., 'Seattle'")] string city,
[Description("Temperature unit: 'celsius' or 'fahrenheit'")] string unit = "celsius")
{
// Call actual weather API
var weather = await _weatherService.GetCurrentAsync(city);
return $"Weather in {city}: {weather.Temperature}° {unit}, {weather.Condition}";
}
[KernelFunction]
[Description("Gets the weather forecast for the next N days")]
public async Task<string> GetForecast(
[Description("The city name")] string city,
[Description("Number of days (1-7)")] int days = 3)
{
var forecast = await _weatherService.GetForecastAsync(city, days);
return FormatForecast(forecast);
}
}
```
### Plugin Best Practices
| Practice | Why It Matters |
|----------|----------------|
| Clear `[Description]` | LLM uses this to decide when to call |
| Specific parameter names | Helps LLM map user intent |
| Idempotent functions | Safe to retry on failures |
| Return meaningful strings | LLM needs to understand results |
| Validate inputs | LLM may hallucinate parameters |
## Function Calling
### Automatic Function Calling
```csharp
var settings = new OpenAIPromptExecutionSettings
{
FunctionChoiceBehavior = FunctionChoiceBehavior.Auto()
};
kernel.Plugins.AddFromObject(new WeatherPlugin(), "Weather");
kernel.Plugins.AddFromObject(new OrderPlugin(), "Orders");
var result = await kernel.InvokePromptAsync(
"What's the weather in Seattle and do I have any pending orders?",
new KernelArguments(settings));
```
### Manual Function Selection
```csharp
var settings = new OpenAIPromptExecutionSettings
{
FunctionChoiceBehavior = FunctionChoiceBehavior.Required(
[kernel.Plugins["Weather"]["GetWeather"]])
};
```
## Chat Completion Patterns
### Multi-Turn Conversation
```csharp
var chatService = kernel.GetRequiredService<IChatCompletionService>();
var history = new ChatHistory();
history.AddSystemMessage("You are a helpful assistant.");
history.AddUserMessage(userMessage);
var response = await chatService.GetChatMessageContentAsync(
history,
executionSettings: new OpenAIPromptExecutionSettings
{
FunctionChoiceBehavior = FunctionChoiceBehavior.Auto()
},
kernel: kernel);
history.AddAssistantMessage(response.Content!);
```
### Streaming Response
```csharp
await foreach (var chunk in chatService.GetStreamingChatMessageContentsAsync(
history, executionSettings, kernel))
{
Console.Write(chunk.Content);
}
```
## Multi-Agent Plugin Isolation
```csharp
// WRONG - agents share plugins
var sharedKernel = Kernel.CreateBuilder().Build();
sharedKernel.Plugins.AddFromObject(new AllPlugins());
var agent1 = new ChatCompletionAgent { Kernel = sharedKernel };
var agent2 = new ChatCompletionAgent { Kernel = sharedKernel };
// Both agents have same plugins!
// CORRECT - isolated kernels
var kernel1 = CreateKernelForAgent1();
kernel1.Plugins.AddFromObject(new WeatherPlugin());
var kernel2 = CreateKernelForAgent2();
kernel2.Plugins.AddFromObject(new OrderPlugin());
var agent1 = new ChatCompletionAgent { Kernel = kerBuild, debug, modernize, or review ASP.NET Core applications with correct hosting, middleware, security, configuration, logging, and deployment patterns on current .NET. USE FOR: working on ASP.NET Core apps, services, or middleware; changing auth, routing, configuration, hosting, or deployment behavior; deciding between ASP.NET Core sub-stacks. DO NOT USE FOR: unrelated stacks; generic tasks that do not need this specific guidance. INVOKES: inspect the repository context, edit targeted files, and run relevant build, test, lint, or validation commands when changes are made.
Build, upgrade, and operate .NET Aspire 13.3.x application hosts with current CLI, AppHost, ServiceDefaults, integrations, dashboard, testing, and Azure deployment patterns for distributed apps. USE FOR: Aspire.AppHost.Sdk, Aspire.Hosting.*, DistributedApplication.CreateBuilder, WithReference, WaitFor, AddProject, AddRedis, AddPostgres, aspire run, aspire init, aspire. DO NOT USE FOR: unrelated stacks; generic tasks that do not need this specific guidance. INVOKES: inspect the repository context, edit targeted files, and run relevant build, test, lint, or validation commands when changes are made.
Build, review, or migrate Azure Functions in .NET with correct execution model, isolated worker setup, bindings, DI, and Durable Functions patterns. USE FOR: working on Azure Functions in .NET; migrating from the in-process model to the isolated worker model; adding Durable Functions, bindings, or host configuration. DO NOT USE FOR: unrelated stacks; generic tasks that do not need this specific guidance. INVOKES: inspect the repository context, edit targeted files, and run relevant build, test, lint, or validation commands when changes are made.
Build and review Blazor applications across server, WebAssembly, web app, and hybrid scenarios with correct component design, state flow, rendering, and hosting choices. USE FOR: building interactive web UIs with C# instead of JavaScript; choosing between Server, WebAssembly, or Auto render modes; designing component hierarchies and state. DO NOT USE FOR: unrelated stacks; generic tasks that do not need this specific guidance. INVOKES: inspect the repository context, edit targeted files, and run relevant build, test, lint, or validation commands when changes are made.
Maintain or migrate EF6-based applications with realistic guidance on what to keep, what to modernize, and when EF Core is or is not the right next step. USE FOR: EF6 codebases; runtime versus ORM migration decisions; EDMX, code-first, ObjectContext, and legacy data-access review. DO NOT USE FOR: unrelated stacks; generic tasks that do not need this specific guidance. INVOKES: inspect the repository context, edit targeted files, and run relevant build, test, lint, or validation commands when changes are made.
Design, tune, or review EF Core data access with proper modeling, migrations, query translation, performance, and lifetime management for modern .NET applications. USE FOR: DbContext, migrations, model configuration, EF queries, tracking, loading, performance, transactions, and EF6 migration decisions. DO NOT USE FOR: unrelated stacks; generic tasks that do not need this specific guidance. INVOKES: inspect the repository context, edit targeted files, and run relevant build, test, lint, or validation commands when changes are made.
Build, review, or migrate .NET MAUI applications across Android, iOS, macOS, and Windows with correct cross-platform UI, platform integration, and native packaging assumptions. USE FOR: working on cross-platform mobile or desktop UI in .NET MAUI; integrating device capabilities, navigation, or platform-specific code; migrating Xamarin.Forms or aligning. DO NOT USE FOR: unrelated stacks; generic tasks that do not need this specific guidance. INVOKES: inspect the repository context, edit targeted files, and run relevant build, test, lint, or validation commands when changes are made.
Use ML.NET to train, evaluate, or integrate machine-learning models into .NET applications with realistic data preparation, inference, and deployment expectations. USE FOR: ML.NET integration; local model training or retraining; inference pipelines, model loading, evaluation, and deployment review. DO NOT USE FOR: unrelated stacks; generic tasks that do not need this specific guidance. INVOKES: inspect the repository context, edit targeted files, and run relevant build, test, lint, or validation commands when changes are made.