SIGN IN SIGN UP

Integrate cutting-edge LLM technology quickly and easily into your apps

0 0 32 C#
Python: Add ability to clone a kernel (#11680) ### Motivation and Context <!-- Thank you for your contribution to the semantic-kernel repo! Please help reviewers and future users, providing the following information: 1. Why is this change required? 2. What problem does it solve? 3. What scenario does it contribute to? 4. If it fixes an open issue, please link to the issue here. --> Currently, we don't have a dedicated method to create a clone of a kernel instance. Using `model_copy(deep=True)` will result in an error because some service clients aren't serializable. Being able to clone a kernel will be critical in many scenarios where developers don't want to mutate the original one that is attached to an agent or some other objects. ### Description <!-- Describe your changes, the overall approach, the underlying design. These notes will help understanding how your code works. Thanks! --> 1. Create a clone method in the `Kernel` class that will return a new instance of the kernel with the same configuration, including the list of filters, plugins and the AI selector. It will also include the same list of services references. 2. Add unit tests and integration tests to ensure the new method works as expected. ### Contribution Checklist <!-- Before submitting this PR, please make sure: --> - [x] The code builds clean without any errors or warnings - [x] The PR follows the [SK Contribution Guidelines](https://github.com/microsoft/semantic-kernel/blob/main/CONTRIBUTING.md) and the [pre-submission formatting script](https://github.com/microsoft/semantic-kernel/blob/main/CONTRIBUTING.md#development-scripts) raises no violations - [x] All unit tests pass, and I have added new tests where possible - [x] I didn't break anyone :smile:
2025-04-23 17:26:51 -07:00
# Copyright (c) Microsoft. All rights reserved.
import pytest
from semantic_kernel.connectors.ai.open_ai.services.open_ai_chat_completion import OpenAIChatCompletion
from semantic_kernel.kernel import Kernel
def test_kernel_deep_copy_fail_with_services():
kernel = Kernel()
kernel.add_service(OpenAIChatCompletion())
with pytest.raises(TypeError):
# This will fail because OpenAIChatCompletion is not serializable, more specifically,
# the client is not serializable
kernel.model_copy(deep=True)
async def test_kernel_clone():
kernel = Kernel()
kernel.add_service(OpenAIChatCompletion())
kernel_clone = kernel.clone()
assert kernel_clone is not None
assert kernel_clone.services is not None and len(kernel_clone.services) > 0
function_result = await kernel.invoke_prompt("Hello World")
assert function_result is not None
assert function_result.value is not None
assert len(str(function_result)) > 0