Building a Simple Semantic Kernel Agent in C#

Introduction

Microsoft’s Semantic Kernel is a powerful framework that enables developers to integrate large language models (LLMs) into their applications seamlessly. Whether you’re building chatbots, content generators, or intelligent automation tools, Semantic Kernel provides the building blocks to create sophisticated AI-powered agents.

In this post, we’ll explore how to build a simple yet effective Semantic Kernel agent in C# that can understand user requests, plan actions, and execute tasks autonomously.

What is Semantic Kernel?

Semantic Kernel is an open-source SDK that allows developers to:

  • Integrate AI services like OpenAI GPT, Azure OpenAI, and other language models
  • Create plugins that extend AI capabilities with custom functions
  • Build AI agents that can plan and execute multi-step tasks
  • Combine traditional programming with AI-powered natural language processing

Think of it as a bridge between your application logic and AI services, providing a structured way to build intelligent applications.

Why Do You Need an Agent?

Traditional AI integrations often involve simple request-response patterns. However, agents take this a step further by:

  • Autonomous Decision Making: Agents can analyze user requests and determine the best course of action
  • Multi-step Planning: They can break down complex tasks into smaller, manageable steps
  • Tool Integration: Agents can use various tools and APIs to accomplish goals
  • Context Awareness: They maintain conversation context and can reference previous interactions

Building a Simple Semantic Kernel Agent

Let’s create a basic agent that can help with file operations and web searches. Here’s a minimal working example:

Step 1: Install Required Packages

First, install the necessary NuGet packages:

dotnet add package Microsoft.SemanticKernel
dotnet add package Microsoft.SemanticKernel.Plugins.Core

Step 2: Create the Agent

using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.ChatCompletion;
using Microsoft.SemanticKernel.Connectors.OpenAI;
using System.ComponentModel;

public class SimpleSemanticKernelAgent
{
    private readonly Kernel _kernel;
    private readonly IChatCompletionService _chatService;
    private readonly ChatHistory _chatHistory;

    public SimpleSemanticKernelAgent(string apiKey, string model = "gpt-3.5-turbo")
    {
        // Create kernel builder
        var builder = Kernel.CreateBuilder();

        // Add OpenAI chat completion service
        builder.AddOpenAIChatCompletion(model, apiKey);

        // Add plugins
        builder.Plugins.AddFromType<FileOperationsPlugin>();
        builder.Plugins.AddFromType<WebSearchPlugin>();

        // Build kernel
        _kernel = builder.Build();

        // Get chat completion service
        _chatService = _kernel.GetRequiredService<IChatCompletionService>();

        // Initialize chat history
        _chatHistory = new ChatHistory();
        _chatHistory.AddSystemMessage(
            "You are a helpful assistant that can perform file operations and web searches. " +
            "When users ask for help, analyze their request and use the available tools to assist them.");
    }

    public async Task<string> ProcessUserRequestAsync(string userInput)
    {
        try
        {
            // Add user message to history
            _chatHistory.AddUserMessage(userInput);

            // Configure execution settings
            var executionSettings = new OpenAIPromptExecutionSettings
            {
                ToolCallBehavior = ToolCallBehavior.AutoInvokeKernelFunctions,
                MaxTokens = 1000,
                Temperature = 0.7
            };

            // Get response from the agent
            var response = await _chatService.GetChatMessageContentAsync(
                _chatHistory, 
                executionSettings, 
                _kernel);

            // Add assistant response to history
            _chatHistory.AddAssistantMessage(response.Content ?? "");

            return response.Content ?? "I'm sorry, I couldn't process your request.";
        }
        catch (Exception ex)
        {
            return $"An error occurred: {ex.Message}";
        }
    }
}

// Example plugin for file operations
public class FileOperationsPlugin
{
    [KernelFunction, Description("Read content from a text file")]
    public async Task<string> ReadFileAsync(
        [Description("Path to the file to read")] string filePath)
    {
        try
        {
            if (!File.Exists(filePath))
                return "File not found.";

            return await File.ReadAllTextAsync(filePath);
        }
        catch (Exception ex)
        {
            return $"Error reading file: {ex.Message}";
        }
    }

    [KernelFunction, Description("Write content to a text file")]
    public async Task<string> WriteFileAsync(
        [Description("Path to the file to write")] string filePath,
        [Description("Content to write to the file")] string content)
    {
        try
        {
            await File.WriteAllTextAsync(filePath, content);
            return "File written successfully.";
        }
        catch (Exception ex)
        {
            return $"Error writing file: {ex.Message}";
        }
    }
}

// Example plugin for web search (simplified)
public class WebSearchPlugin
{
    [KernelFunction, Description("Search the web for information")]
    public async Task<string> SearchWebAsync(
        [Description("Search query")] string query)
    {
        // In a real implementation, you would integrate with a search API
        // like Bing Search API, Google Custom Search, etc.
        await Task.Delay(1000); // Simulate API call

        return $"Search results for '{query}': [This is a simplified example. " +
               "In a real implementation, you would return actual search results.]";;
    }
}

Step 3: Using the Agent

class Program
{
    static async Task Main(string[] args)
    {
        // Initialize the agent with your OpenAI API key
        var agent = new SimpleSemanticKernelAgent("your-openai-api-key-here");

        Console.WriteLine("Semantic Kernel Agent initialized. Type 'exit' to quit.");

        while (true)
        {
            Console.Write("\nYou: ");
            var input = Console.ReadLine();

            if (input?.ToLower() == "exit")
                break;

            if (string.IsNullOrWhiteSpace(input))
                continue;

            Console.Write("Agent: ");
            var response = await agent.ProcessUserRequestAsync(input);
            Console.WriteLine(response);
        }
    }
}

Important Tips for Success

When building Semantic Kernel agents, keep these best practices in mind:

1. Design Clear Function Descriptions

  • Use descriptive function names and detailed descriptions
  • Provide clear parameter descriptions
  • Include examples in your documentation

2. Handle Errors Gracefully

  • Always wrap plugin functions in try-catch blocks
  • Return meaningful error messages
  • Log errors for debugging purposes

3. Optimize Performance

  • Use appropriate token limits to control costs
  • Implement caching for frequently used data
  • Consider using streaming responses for long operations

4. Security Considerations

  • Validate all inputs to your plugins
  • Implement proper authentication and authorization
  • Be cautious with file system access and external API calls
  • Never expose sensitive information in function descriptions

5. Testing and Monitoring

  • Test your agent with various input scenarios
  • Monitor token usage and API costs
  • Implement logging to track agent behavior
  • Use A/B testing to improve agent responses

Summary

Semantic Kernel agents represent a powerful way to build intelligent applications that can understand natural language, plan actions, and execute tasks autonomously. The example we’ve built demonstrates the core concepts:

  • Kernel Configuration: Setting up the AI service and plugins
  • Plugin Development: Creating custom functions the agent can use
  • Conversation Management: Maintaining context across interactions
  • Error Handling: Gracefully managing failures and edge cases

With these foundations, you can extend the agent to support more complex scenarios, integrate with additional APIs, and create sophisticated AI-powered applications that truly understand and assist your users.

The future of software development increasingly involves AI collaboration, and Semantic Kernel provides an excellent framework for building these intelligent partnerships. Start simple, iterate quickly, and gradually add more capabilities as your understanding and requirements grow.

Introduction to Autogen

In the rapidly evolving world of artificial intelligence, developers are constantly seeking tools that can streamline complex workflows and enable sophisticated automation. Enter Autogen – an innovative open-source multi-agent AI framework that’s transforming how we approach AI-driven projects.

What is Autogen?

Autogen is a powerful, open-source framework designed for building multi-agent conversational AI systems. Developed and supported by Microsoft, this framework enables developers to create sophisticated workflows where multiple AI agents can collaborate, communicate, and work together to accomplish complex tasks that would be challenging for a single AI system to handle alone.

At its core, Autogen facilitates the orchestration of multiple AI agents, each potentially with different roles, capabilities, and specializations, allowing them to engage in meaningful conversations and collaborative problem-solving.

Key Features That Make Autogen Stand Out

Multi-Agent Architecture: Unlike traditional single-agent systems, Autogen excels at managing multiple AI agents simultaneously, enabling them to work together in coordinated workflows.

Extensible and Composable Design: One of Autogen’s greatest strengths is its modular architecture. Developers can easily extend existing functionality, compose new agent behaviors, and customize workflows to meet specific requirements.

Conversational AI Capabilities: The framework provides robust support for natural language interactions between agents, making it ideal for applications requiring sophisticated dialogue management.

Integration-Friendly: Autogen is designed to work seamlessly with existing AI models and APIs, allowing developers to leverage their preferred language models and tools.

Strong Community Support: As an open-source project backed by Microsoft, Autogen benefits from a vibrant community of contributors, extensive documentation, and regular updates.

Why Developers Choose Autogen

Developers are drawn to Autogen for several compelling reasons:

Simplified Complex Workflows: Tasks that previously required intricate coordination between different systems can now be handled elegantly through multi-agent conversations.

Reduced Development Time: The framework’s composable nature means developers can build upon existing components rather than starting from scratch.

Scalability: Multi-agent systems can distribute workloads and handle complex scenarios more efficiently than monolithic solutions.

Flexibility: The open-source nature allows for complete customization and adaptation to specific use cases.

Real-World Applications

Autogen’s versatility makes it valuable across numerous domains:

Automation: Streamlining business processes through intelligent agent coordination, from data processing pipelines to customer service workflows.

Research: Facilitating collaborative research where different agents can specialize in various aspects of a research problem, from data collection to analysis and report generation.

Education: Creating interactive learning environments where multiple teaching agents can provide personalized instruction and support.

Content Creation: Coordinating agents for writing, editing, and reviewing content across different formats and domains.

Software Development: Enabling code review processes, automated testing coordination, and development workflow optimization.

Getting Started

For developers interested in exploring Autogen, the framework offers comprehensive documentation, tutorials, and examples on both the official documentation and Microsoft’s GitHub repository. The community-driven nature of the project ensures continuous improvement and extensive support resources.

Whether you’re building automation tools, research platforms, educational applications, or any system requiring sophisticated AI coordination, Autogen provides the foundation for creating powerful, scalable multi-agent solutions.

As AI continues to evolve, frameworks like Autogen are paving the way for more collaborative, intelligent systems that can tackle increasingly complex challenges through the power of multi-agent cooperation.