How to beginner · 3 min read

Semantic Kernel environment setup

Quick answer
Set up the semantic_kernel Python package by installing it via pip and configure an OpenAIChatCompletion service with your OpenAI API key. Initialize a Kernel instance, add the OpenAI service, and you are ready to run Semantic Kernel AI tasks.

PREREQUISITES

  • Python 3.8+
  • OpenAI API key (free tier works)
  • pip install semantic-kernel openai

Setup

Install the semantic_kernel package along with openai for OpenAI API access. Set your OpenAI API key as an environment variable OPENAI_API_KEY before running your code.

bash
pip install semantic-kernel openai

Step by step

This example shows how to initialize the Semantic Kernel, add the OpenAI chat completion service, and run a simple prompt to get a response.

python
import os
import semantic_kernel as sk
from semantic_kernel.connectors.ai.open_ai import OpenAIChatCompletion

# Ensure your OpenAI API key is set in environment variables
api_key = os.environ["OPENAI_API_KEY"]

# Create the kernel instance
kernel = sk.Kernel()

# Add OpenAI chat completion service with model gpt-4o-mini
kernel.add_service(OpenAIChatCompletion(
    service_id="chat",
    api_key=api_key,
    ai_model_id="gpt-4o-mini"
))

# Define a simple prompt
prompt = "Write a short poem about AI."

# Run the prompt through the kernel's chat service
response = kernel.run(prompt, service_id="chat")

print("Response:", response)
output
Response: AI weaves dreams in code and light,
Silent thinker through the night.
Endless knowledge, swift and bright,
Guiding futures, taking flight.

Common variations

  • Use different AI models by changing ai_model_id (e.g., gpt-4o or gpt-4o-mini).
  • For asynchronous calls, use await kernel.run_async(...) inside an async function.
  • Integrate other AI services by adding different connectors to the kernel.

Troubleshooting

  • If you see KeyError for OPENAI_API_KEY, ensure the environment variable is set correctly.
  • For authentication errors, verify your API key is valid and has access to the specified model.
  • If the kernel fails to run, check that semantic_kernel and openai packages are up to date.

Key Takeaways

  • Install semantic_kernel and openai packages to start using Semantic Kernel in Python.
  • Configure the kernel by adding an OpenAI chat completion service with your API key and preferred model.
  • Use kernel.run() for synchronous calls and kernel.run_async() for async execution.
  • Always set your OPENAI_API_KEY environment variable before running your code.
  • Update packages regularly to avoid compatibility issues and access new features.
Verified 2026-04 · gpt-4o-mini
Verify ↗