Semantic Kernel concepts explained
Quick answer
The semantic_kernel is a Python SDK that provides a modular framework to build AI applications by combining kernels, skills, and AI services. A kernel manages AI models and orchestrates skills, which are reusable units of AI logic, enabling structured and composable AI workflows.
PREREQUISITES
Python 3.8+OpenAI API key (free tier works)pip install semantic-kernel openai
Setup
Install the semantic-kernel Python package and set your OpenAI API key as an environment variable.
- Run
pip install semantic-kernel openai - Set environment variable
OPENAI_API_KEYwith your OpenAI API key
pip install semantic-kernel openai Step by step
This example shows how to create a Kernel, add an OpenAI chat completion service, define a simple skill with a prompt, and invoke it.
import os
import semantic_kernel as sk
from semantic_kernel.connectors.ai.open_ai import OpenAIChatCompletion
# Initialize kernel
kernel = sk.Kernel()
# Add OpenAI chat completion service
kernel.add_service(OpenAIChatCompletion(
service_id="chat",
api_key=os.environ["OPENAI_API_KEY"],
ai_model_id="gpt-4o-mini"
))
# Define a simple skill function
prompt = "Tell me a joke about {topic}."
skill = kernel.create_semantic_function(
prompt_template=prompt,
skill_name="JokeSkill",
function_name="TellJoke"
)
# Invoke the skill
result = skill.invoke_async({"topic": "programming"}).result()
print("Joke:", result) output
Joke: Why do programmers prefer dark mode? Because light attracts bugs!
Common variations
You can use different AI services like Azure OpenAI or Anthropic by adding their connectors to the kernel. Skills can be composed into workflows, and you can use synchronous or asynchronous invocation. You can also load skills from external files or directories for modularity.
import asyncio
# Async invocation example
async def async_example():
result = await skill.invoke_async({"topic": "AI"})
print("Async joke:", result)
asyncio.run(async_example()) output
Async joke: Why did the AI go to art school? Because it loved to draw conclusions!
Troubleshooting
- If you see authentication errors, verify your
OPENAI_API_KEYenvironment variable is set correctly. - If prompts fail, check your prompt template syntax and ensure the AI model ID matches available models.
- For network issues, confirm internet connectivity and firewall settings.
Key Takeaways
- Kernel is the core orchestrator managing AI services and skills.
- Skills are reusable AI prompt functions that encapsulate logic.
- You can add multiple AI services to the kernel for flexible model usage.
- Invoke skills synchronously or asynchronously for integration flexibility.
- Proper environment setup and API keys are essential for smooth operation.