Skip to content
BotServBotServ
Semantic KernelMicrosoftAgent FrameworkPluginsPlanner

Semantic Kernel: Microsoft's Agent Framework

Semantic Kernel for AI agents. Microsoft's framework for agents, plugins, planner and practical examples.

S

schutzgeist

4 min read
Semantic Kernel: Microsoft's Agent Framework

Semantic Kernel: Microsoft’s Agent Framework

What This Article Covers

  • What Semantic Kernel is and how it works.
  • Building agents with Semantic Kernel.
  • Plugins, planners, and memory for agents.
  • Real-world examples across different use cases.
  • Best practices for enterprise integration and production.

Introduction: Understanding Semantic Kernel

Semantic Kernel is Microsoft’s framework for building AI agents. It connects LLMs with plugins (tools), planners (orchestration), and memory (context). Designed for enterprise applications in .NET and Python.

This article is for developers looking to build agents with Semantic Kernel. For foundational concepts, see AI Agent Frameworks and LangChain.

Why Use Semantic Kernel?

Consider building an enterprise agent that needs to work with your CRM, ERP, and internal APIs. Semantic Kernel provides enterprise integration, planners for complex workflows, and memory management for context. For Microsoft-based technology stacks, it’s the natural choice.

Semantic Kernel at a Glance

Semantic Kernel is Microsoft’s agent framework. It provides plugins for tooling, planners for orchestration, and memory for context management. Built for .NET and Python with an enterprise focus.

The core idea: enterprise-grade infrastructure for AI agents.

Who This Article Is For

  • .NET developers building agents.
  • Enterprise teams running on Microsoft stacks.
  • Python developers using SK for agents.
  • DevOps engineers deploying agents in enterprise environments.

Key Concepts

  • Semantic Kernel - Microsoft’s agent framework. Use when: building enterprise agents.
  • Plugin - Tool or integration. Use when: adding functionality.
  • Planner - Orchestration engine. Use when: handling complex workflows.
  • Memory - Context storage. Use when: maintaining state.
  • Ollama - Local model server. Use when: running local models.

Setup

Python

pip install semantic-kernel
from semantic_kernel import Kernel
from semantic_kernel.connectors.ai.open_ai import OpenAIChatCompletion

# Create kernel
kernel = Kernel()

# Add LLM (Ollama)
kernel.add_service(OpenAIChatCompletion(
    service_id="ollama",
    ai_model_id="llama3.1",
    endpoint="http://ollama:11434/v1",
    api_key="not-needed"
))

C# / .NET

using Microsoft.SemanticKernel;

// Create kernel
var kernel = Kernel.CreateBuilder()
    .AddOpenAIChatCompletion(
        modelId: "llama3.1",
        endpoint: new Uri("http://ollama:11434/v1"),
        apiKey: "not-needed")
    .Build();

Example 1: Creating a Plugin

from semantic_kernel.functions import kernel_function

class MyPlugin:
    """Custom plugin for Semantic Kernel"""

    @kernel_function(
        name="get_weather",
        description="Fetch weather information"
    )
    def get_weather(self, location: str) -> str:
        """Get weather for a location"""
        # API call
        return f"Weather in {location}: 22°C, sunny"

    @kernel_function(
        name="send_email",
        description="Send an email"
    )
    def send_email(self, to: str, subject: str, body: str) -> str:
        """Send an email"""
        # Email logic
        return f"Email sent to {to}"

# Add plugin to kernel
kernel.add_plugin(MyPlugin(), plugin_name="my_plugin")

Example 2: Planner for Complex Workflows

from semantic_kernel.planners import SequentialPlanner

# Create planner
planner = SequentialPlanner(kernel)

# Define goal
goal = "Research the topic, analyze the data, and write a report."

# Create plan
plan = await planner.create_plan_async(goal)

# Execute plan
result = await plan.invoke_async()

Example 3: Memory for Context

from semantic_kernel.memory import SemanticTextMemory
from semantic_kernel.connectors.ai.open_ai import OpenAITextEmbedding

# Add memory
memory = SemanticTextMemory(
    storage=VolatileMemoryStore(),
    embeddings_generator=OpenAITextEmbedding(
        service_id="embeddings",
        ai_model_id="text-embedding-ada-002",
        endpoint="http://ollama:11434/v1",
        api_key="not-needed"
    )
)

# Store information
await memory.save_information_async(
    collection="documents",
    text="Customer Max Mustermann placed an order on 15.03.",
    id="doc1"
)

# Retrieve information
results = await memory.search_async(
    collection="documents",
    query="When did Max place an order?"
)

Example 4: Agent with Plugins and Memory

class SemanticKernelAgent:
    """Agent built with Semantic Kernel"""

    def __init__(self):
        self.kernel = Kernel()
        self.setup_services()
        self.setup_plugins()
        self.setup_memory()

    async def run(self, task):
        """Agent loop"""
        # Retrieve memory (context)
        context = await self.memory.search_async(
            collection="context",
            query=task
        )

        # Invoke plugin or LLM directly
        if self.needs_tool(task):
            result = await self.kernel.invoke_async(
                plugin_name="my_plugin",
                function_name="relevant_function",
                task=task,
                context=context
            )
        else:
            result = await self.llm.complete_async(task, context)

        # Save to memory
        await self.memory.save_information_async(
            collection="context",
            text=f"Task: {task}, Result: {result}",
            id=f"task_{datetime.now().isoformat()}"
        )

        return result

Semantic Kernel vs. LangChain

AspectSemantic KernelLangChain
LanguagesC#, PythonPython, JavaScript
FocusEnterpriseGeneral purpose
PlannerYes, dedicatedNo, manual
MemoryYes, dedicatedYes, various options
IntegrationMicrosoft StackMany integrations
CommunityGrowingLarge
Best forEnterprise, .NETGeneral agents

Security Considerations

  • API Keys: For OpenAI APIs, use environment variables, never hardcode.
  • Plugin Permissions: Plugins should validate permissions. See MCP Permissions.
  • Memory Security: Memory may contain sensitive data. Store securely.
  • Audit: Log all agent actions. See Audit Logging.

Common Pitfalls

  • Complex Planners: Planners can generate intricate, hard-to-understand execution plans. Keep goals simple.
  • Memory Growth: Memory can grow large over time. Plan a cleanup strategy.
  • Plugin Dependencies: Plugins may depend on external services. Document these.
  • Enterprise vs. Open Source: SK is enterprise-focused. For open-source projects, LangChain or CrewAI may be better fits.
  • .NET vs. Python: SK is stronger in .NET. For Python-only projects, LangChain may be more suitable.

Further Reading

Key Takeaways:

  • Semantic Kernel is Microsoft’s enterprise agent framework.
  • Plugins provide tooling, planners handle orchestration, memory manages context.
  • Built for .NET and Python with an enterprise focus.
  • Ideal for Microsoft-based stacks and enterprise applications.
  • For open-source projects, LangChain or CrewAI might be better choices.

FAQ

What is Semantic Kernel?

Microsoft’s framework for AI agents: plugins for tooling, planners for orchestration, memory for context. Built for .NET and Python with an enterprise focus.

Semantic Kernel or LangChain?

SK for enterprise and .NET. LangChain for general-purpose agents and Python. SK has dedicated planners and memory, LangChain is more flexible.

What are plugins?

Tools and integrations for the agent: CRM, email, APIs, databases. Plugins extend the agent’s capabilities.

What is a planner?

Orchestration for complex workflows: the planner breaks down a goal into steps, selects plugins, and coordinates execution.

What is memory?

Context storage for the agent: stores information, retrieves when needed. Maintains state and continuity across agent invocations.

Do I need .NET?

No, SK is available for Python. However, .NET is the primary language for SK. For Python-only projects, LangChain might be a better fit.

Is SK suitable for enterprise?

Yes, SK is enterprise-focused: integration with Microsoft Stack, planners for complex workflows, memory for context management, and solid documentation.

How much does Semantic Kernel cost?

Free. SK is open source (MIT license). For Azure OpenAI, you pay API costs. For local models, only hardware costs apply.

Sources and Further Reading

Back to Blog
Share:

Related Posts