How to create native functions in Semantic Kernel
Quick answer
In
Semantic Kernel, create native functions by defining Python functions and registering them with the Kernel instance using register_native_function. These functions can then be invoked from AI skills or prompts to extend capabilities with custom logic.PREREQUISITES
Python 3.8+pip install semantic-kernelOpenAI API key (free tier works)pip install openai>=1.0
Setup
Install the semantic-kernel Python package and set your OpenAI API key as an environment variable.
- Install Semantic Kernel:
pip install semantic-kernel - Set environment variable:
export OPENAI_API_KEY='your_api_key'(Linux/macOS) orsetx OPENAI_API_KEY "your_api_key"(Windows)
pip install semantic-kernel Step by step
Define a native Python function and register it with the Kernel. Then invoke it via the kernel's skills interface.
import os
import semantic_kernel as sk
from semantic_kernel.connectors.ai.open_ai import OpenAIChatCompletion
# Initialize kernel and add OpenAI chat service
kernel = sk.Kernel()
kernel.add_service(OpenAIChatCompletion(
service_id="chat",
api_key=os.environ["OPENAI_API_KEY"],
ai_model_id="gpt-4o-mini"
))
# Define a native Python function
@sk.native_function("greet")
def greet(name: str) -> str:
return f"Hello, {name}! Welcome to Semantic Kernel native functions."
# Register the native function with the kernel
kernel.register_native_function(greet)
# Invoke the native function
result = kernel.invoke_native_function("greet", "Alice")
print(result) # Output: Hello, Alice! Welcome to Semantic Kernel native functions. output
Hello, Alice! Welcome to Semantic Kernel native functions.
Common variations
You can create async native functions by defining async Python functions and registering them similarly. Also, native functions can accept multiple parameters and return complex types.
Example async native function:
import asyncio
@sk.native_function("async_greet")
async def async_greet(name: str) -> str:
await asyncio.sleep(0.1) # simulate async work
return f"Hello asynchronously, {name}!"
kernel.register_native_function(async_greet)
# To invoke async native function use asyncio
import asyncio
result = asyncio.run(kernel.invoke_native_function("async_greet", "Bob"))
print(result) # Output: Hello asynchronously, Bob! output
Hello asynchronously, Bob!
Troubleshooting
- If you see
AttributeErroronregister_native_function, ensure you are usingsemantic-kernelversion 1.0 or later. - If native functions do not execute, verify your function is decorated with
@sk.native_functionand properly registered. - For async functions, always invoke with an event loop like
asyncio.run().
Key Takeaways
- Use @sk.native_function decorator to define native functions in Semantic Kernel.
- Register native functions with kernel.register_native_function before invoking.
- Async native functions require async def and invocation via asyncio.run().