How to use Semantic Kernel function calling
Quick answer
Use
semantic_kernel to define and register functions as skills, then invoke them via the kernel instance. Functions are created with kernel.create_semantic_function() and called with kernel.run() or function.invoke().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.
pip install semantic-kernel openai Step by step
This example shows how to create a Semantic Kernel instance, register an OpenAI chat completion service, define a semantic function, and call 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 semantic function with a prompt template
prompt_template = """Write a friendly greeting for the user named {{name}}."""
semantic_function = kernel.create_semantic_function(
prompt_template=prompt_template,
skill_name="GreetingSkill",
function_name="SayHello"
)
# Invoke the function
result = kernel.run(
semantic_function,
input_vars={"name": "Alice"}
)
print("Output:", result) output
Output: Hello Alice! Hope you're having a great day!
Common variations
- Use
function.invoke()directly instead ofkernel.run(). - Switch to a different OpenAI model by changing
ai_model_id. - Use async calls with
await function.invoke_async()in async contexts.
import asyncio
async def async_example():
result = await semantic_function.invoke_async({"name": "Bob"})
print("Async output:", result)
asyncio.run(async_example()) output
Async output: Hello Bob! Hope you're having a great day!
Troubleshooting
- If you see authentication errors, verify your
OPENAI_API_KEYenvironment variable is set correctly. - If the function returns empty or unexpected output, check your prompt template syntax and variable names.
- For model errors, confirm the
ai_model_idmatches a valid OpenAI model likegpt-4o-mini.
Key Takeaways
- Use
kernel.create_semantic_function()to define reusable AI functions with prompt templates. - Invoke functions via
kernel.run()orfunction.invoke()for flexible calling patterns. - Register AI services like OpenAI chat completions with
kernel.add_service()before function creation.