Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions python/semantic_kernel/processes/process_step_builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import logging
import uuid
from dataclasses import is_dataclass
from enum import Enum
from typing import TYPE_CHECKING, Any, Generic

Expand Down Expand Up @@ -174,7 +175,9 @@ def build_step(self, state_metadata: KernelProcessStepStateMetadata | None = Non
if isinstance(candidate, dict):
try:
parsed_state_from_metadata = (
t_state(**candidate) if hasattr(t_state, "__fields__") else t_state()
t_state(**candidate)
if hasattr(t_state, "__fields__") or is_dataclass(t_state)
else t_state()
)
except Exception as ex:
raise KernelException(
Expand All @@ -199,7 +202,7 @@ def build_step(self, state_metadata: KernelProcessStepStateMetadata | None = Non
)

if actual_state is None:
actual_state = t_state() if hasattr(t_state, "__fields__") else t_state
actual_state = t_state()

state_object = KernelProcessStepState[t_state]( # type: ignore
name=self.name, id=self.id, version=version, state=actual_state
Expand Down
27 changes: 18 additions & 9 deletions python/semantic_kernel/processes/process_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,23 +10,32 @@
TState = TypeVar("TState")


def _unwrap_optional(t_state: Any) -> Any:
"""Return the type inside `X | None`, or the type itself."""
# Handle Union types and Python 3.12 '|' syntax explicitly
if get_origin(t_state) in {Union, types.UnionType}:
args = get_args(t_state)
# Filter out 'NoneType' and keep the remaining types
non_none_args = [arg for arg in args if arg is not type(None)]
return non_none_args[0] if non_none_args else None
return t_state


@experimental
def get_generic_state_type(cls) -> Any:
"""Given a subclass of KernelProcessStep, retrieve the concrete type of 'state'."""
try:
type_hints = get_type_hints(cls)
t_state = type_hints.get("state", None)
t_state = _unwrap_optional(type_hints.get("state", None))
if t_state is not None:
# Handle Union types and Python 3.12 '|' syntax explicitly
origin = get_origin(t_state)
if origin in {Union, types.UnionType}:
args = get_args(t_state)
# Filter out 'NoneType' and keep the remaining types
non_none_args = [arg for arg in args if arg is not type(None)]
t_state = non_none_args[0] if non_none_args else None
# Check if t_state is a TypeVar (e.g., TypeVar('TState'))
if isinstance(t_state, TypeVar):
t_state = None # We don't have a concrete type
# A step declared as `KernelProcessStep[MyState]` keeps the TypeVar in its type hints,
# but pydantic has resolved the field annotation to the concrete type.
model_field = getattr(cls, "model_fields", {}).get("state")
t_state = _unwrap_optional(model_field.annotation) if model_field else None
if isinstance(t_state, TypeVar):
t_state = None # We don't have a concrete type
return t_state
except Exception:
pass # nosec
Expand Down
118 changes: 118 additions & 0 deletions python/tests/unit/processes/test_process_step_generic_state.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
# Copyright (c) Microsoft. All rights reserved.

from dataclasses import dataclass

import pytest

from semantic_kernel import Kernel
from semantic_kernel.functions import kernel_function
from semantic_kernel.kernel_pydantic import KernelBaseModel
from semantic_kernel.processes.kernel_process.kernel_process_step import KernelProcessStep
from semantic_kernel.processes.kernel_process.kernel_process_step_state import KernelProcessStepState
from semantic_kernel.processes.kernel_process.kernel_process_step_state_metadata import (
KernelProcessStateMetadata,
KernelProcessStepStateMetadata,
)
from semantic_kernel.processes.local_runtime.local_event import KernelProcessEvent
from semantic_kernel.processes.local_runtime.local_kernel_process import start
from semantic_kernel.processes.process_builder import ProcessBuilder
from semantic_kernel.processes.process_state_metadata_utils import kernel_process_to_process_state_metadata


class CounterState(KernelBaseModel):
count: int = 0


@dataclass
class DataclassCounterState:
count: int = 0


class CounterStep(KernelProcessStep[CounterState]):
"""A step that only names its state type in the base class, like the process samples do for UserInputStep."""

async def activate(self, state: KernelProcessStepState[CounterState]):
state.state = state.state or CounterState()
self.state = state.state

@kernel_function
async def run(self, value: str) -> str:
self.state.count += 1
return value


class DataclassCounterStep(KernelProcessStep[DataclassCounterState]):
async def activate(self, state: KernelProcessStepState[DataclassCounterState]):
state.state = state.state or DataclassCounterState()
self.state = state.state

@kernel_function
async def run(self, value: str) -> str:
self.state.count += 1
return value


def _restore_metadata(step_name: str, state: dict) -> KernelProcessStateMetadata:
return KernelProcessStateMetadata(
name="p",
id=None,
version_info="v1",
steps_state={
step_name: KernelProcessStepStateMetadata(name=step_name, id=None, version_info="v1", state=state)
},
)


@pytest.mark.parametrize(
("step_type", "state_type"),
[(CounterStep, CounterState), (DataclassCounterStep, DataclassCounterState)],
ids=["pydantic", "dataclass"],
)
def test_build_gives_a_parametrized_step_a_default_state(step_type, state_type):
builder = ProcessBuilder(name="p")
builder.add_step(step_type)

process = builder.build()

assert process.steps[0].state.state == state_type()


def test_initial_state_is_accepted_by_a_parametrized_step():
builder = ProcessBuilder(name="p")
builder.add_step(CounterStep, initial_state=CounterState(count=5))

process = builder.build()

assert process.steps[0].state.state == CounterState(count=5)


@pytest.mark.parametrize(
("step_type", "state_type"),
[(CounterStep, CounterState), (DataclassCounterStep, DataclassCounterState)],
ids=["pydantic", "dataclass"],
)
def test_state_metadata_restores_the_state_of_a_parametrized_step(step_type, state_type):
builder = ProcessBuilder(name="p")
builder.add_step(step_type)

process = builder.build(state_metadata=_restore_metadata(step_type.__name__, {"count": 7}))

restored = process.steps[0].state.state
assert isinstance(restored, state_type)
assert restored.count == 7


@pytest.mark.parametrize(
("step_type", "state_type"),
[(CounterStep, CounterState), (DataclassCounterStep, DataclassCounterState)],
ids=["pydantic", "dataclass"],
)
async def test_state_of_a_parametrized_step_is_saved_after_a_run(step_type, state_type):
builder = ProcessBuilder(name="p")
step = builder.add_step(step_type)
builder.on_input_event("go").send_event_to(step, function_name="run", parameter_name="value")

context = await start(process=builder.build(), kernel=Kernel(), initial_event=KernelProcessEvent(id="go", data="x"))
metadata = kernel_process_to_process_state_metadata(await context.get_state())

assert metadata.steps_state[step_type.__name__].state == state_type(count=1)
33 changes: 33 additions & 0 deletions python/tests/unit/processes/test_process_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
from typing import TypeVar
from unittest.mock import patch

from semantic_kernel.kernel_pydantic import KernelBaseModel
from semantic_kernel.processes.kernel_process.kernel_process_step import KernelProcessStep
from semantic_kernel.processes.process_types import get_generic_state_type


Expand Down Expand Up @@ -72,3 +74,34 @@ def test_get_generic_state_type_exception():
with patch("semantic_kernel.processes.process_types.get_type_hints", side_effect=Exception("Mocked exception")):
result = get_generic_state_type(ConcreteKernelProcessStep)
assert result is None


class PydanticState(KernelBaseModel):
value: int = 0


class ParametrizedKernelProcessStep(KernelProcessStep[PydanticState]):
pass


class InheritedParametrizedKernelProcessStep(ParametrizedKernelProcessStep):
pass


class UnparametrizedKernelProcessStep(KernelProcessStep):
pass


def test_get_generic_state_type_parametrized_step():
result = get_generic_state_type(ParametrizedKernelProcessStep)
assert result is PydanticState


def test_get_generic_state_type_inherited_parametrized_step():
result = get_generic_state_type(InheritedParametrizedKernelProcessStep)
assert result is PydanticState


def test_get_generic_state_type_unparametrized_step():
result = get_generic_state_type(UnparametrizedKernelProcessStep)
assert result is None
Loading