ValueError
semantic_kernel.kernel.KernelError: Service not added to kernel
Stack trace
Traceback (most recent call last):
File "app.py", line 42, in <module>
kernel.get_service("text_completion")
File "semantic_kernel/kernel.py", line 210, in get_service
raise KernelError("Service not added to kernel")
semantic_kernel.kernel.KernelError: Service not added to kernel Why it happens
Semantic Kernel requires all AI services (like text completion or embeddings) to be explicitly added to the kernel before use. This error happens when your code attempts to access a service that was never registered, causing the kernel to raise an exception.
Detection
Check your kernel initialization code to ensure all required services are added before calling them. Logging kernel service registrations can help detect missing services early.
Causes & fixes
The AI service (e.g., text completion) was never added to the kernel instance.
Add the required service to the kernel using kernel.add_service() or the appropriate method before accessing it.
Typo or mismatch in the service name when retrieving it from the kernel.
Verify the exact service name string matches the one used during registration, including case sensitivity.
Kernel initialization code runs after the service retrieval call, causing the service to be missing at access time.
Ensure the kernel and its services are fully initialized before any service calls by reordering your code.
Code: broken vs fixed
from semantic_kernel import Kernel
kernel = Kernel()
# Missing: kernel.add_service('text_completion', service_instance)
result = kernel.get_service('text_completion').complete('Hello') # This line raises the error import os
from semantic_kernel import Kernel
from semantic_kernel.ai.open_ai import OpenAITextCompletion
os.environ['OPENAI_API_KEY'] = os.environ.get('OPENAI_API_KEY') # Ensure your API key is set
kernel = Kernel()
text_completion = OpenAITextCompletion(api_key=os.environ['OPENAI_API_KEY'])
kernel.add_service('text_completion', text_completion) # Added service registration
result = kernel.get_service('text_completion').complete('Hello')
print(result) # This works now Workaround
Wrap the service retrieval in try/except, and if the service is missing, initialize and add it dynamically before retrying the call.
Prevention
Always register all required AI services with the kernel during initialization and validate service availability before usage to avoid runtime errors.