Article
semantic-kernelpythonllm-orchestrationfunction-callingpluginsmicrosoftsdkagent
Orchestrate LLM Skills with Semantic Kernel in Python
Semantic Kernel is Microsoft's SDK for orchestrating LLMs. This guide shows you how to define a native function (a 'plugin'), create a kernel, and have the AI intelligently call your function to answer a user's prompt.
beginner15 min4 steps
The play
- Install and Configure EnvironmentInstall the necessary Python libraries. Semantic Kernel uses an API key for the LLM service (like OpenAI). Create a `.env` file in your project root to store your key securely.
- Initialize the KernelThe `Kernel` is the core orchestrator in Semantic Kernel. Instantiate it and add a chat service. This connects your application to a specific LLM, like GPT-4, which will be used for reasoning.
- Create a Native PluginPlugins are how you extend the AI's capabilities. Create a simple Python class and use the `@kernel_function` decorator on its methods. This exposes your native code to the kernel, making it a tool the AI can use.
- Import Plugin and Invoke KernelAdd your plugin to the kernel so the AI knows about it. Then, invoke the kernel with a prompt. Semantic Kernel's planner will analyze the prompt, see that it needs to use your `LightPlugin`, execute it, and use the result to form a final answer.
Starter code
import asyncio
import os
from dotenv import load_dotenv
import semantic_kernel as sk
from semantic_kernel.functions.kernel_function_decorator import kernel_function
# 1. Define a native plugin with a function the AI can call
class LightPlugin:
"""A simple plugin to control a light."""
is_on = False
@kernel_function(
name="change_state",
description="Changes the state of the light to on or off."
)
def change_state(self, new_state: bool) -> str:
"""Sets the light to a new state and returns the status."""
self.is_on = new_state
status = "on" if self.is_on else "off"
# This print statement shows the function was actually executed
print(f"--- Native function LightPlugin.change_state called: Light is now {status} ---")
return f"The light has been successfully turned {status}."
async def main():
# 2. Load environment variables from a .env file
# Create a .env file with: OPENAI_API_KEY="sk-..."
load_dotenv()
# 3. Initialize the Semantic Kernel
kernel = sk.Kernel()
api_key = os.getenv("OPENAI_API_KEY")
if not api_key:
print("OpenAI API key not found. Please set it in your .env file.")
return
# 4. Add the OpenAI chat service to the kernel
kernel.add_chat_service(
"chat_service",
sk.connectors.ai.open_ai.OpenAIChatCompletion("gpt-4", api_key),
)
# 5. Import the plugin into the kernel
kernel.add_plugin(LightPlugin(), "lights")
# 6. Run the kernel with a prompt that requires the plugin
prompt = "Hey, can you turn the light on?"
print(f"User > {prompt}")
# The kernel will automatically detect the need for the 'lights.change_state' function
result = await kernel.invoke_prompt(prompt)
print(f"Assistant > {result}")
if __name__ == "__main__":
asyncio.run(main())