Skip to content

Commit f61714c

Browse files
moonbox3Javier
authored andcommitted
Python: Allow enums to be passed in to on_function_result. Improve handling FRC result so it can be hashed. (microsoft#10316)
### Motivation and Context Two topics in this PR: - A request to be able to pass in Enums to the Python process `on_function_result`, instead of just strings. - There were some custom types (Pydantic models) that were unable to hash during an agent group chat. One could mark the model `frozen` so that it is hashable; however, we should add better handling in our code, in case a dev doesn't want to do that. <!-- 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. --> ### Description This PR: - checks if the function name in `on_function_result` in our process framework is an enum, if so, convert to a string. - improves the parsing of the `result` in `FunctionResultContent` so that it can be included in the hash function during an agent group chat. Adding tests to handle multiple different scenarios. - Closes microsoft#10299 - Closes microsoft#10305 <!-- Describe your changes, the overall approach, the underlying design. These notes will help understanding how your code works. Thanks! --> ### 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 😄
1 parent 665a363 commit f61714c

5 files changed

Lines changed: 159 additions & 4 deletions

File tree

‎python/semantic_kernel/contents/function_result_content.py‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
from semantic_kernel.contents.kernel_content import KernelContent
1313
from semantic_kernel.contents.text_content import TextContent
1414
from semantic_kernel.contents.utils.author_role import AuthorRole
15+
from semantic_kernel.contents.utils.hashing import make_hashable
1516
from semantic_kernel.exceptions.content_exceptions import ContentInitializationError
1617

1718
if TYPE_CHECKING:
@@ -194,10 +195,11 @@ def serialize_result(self, value: Any) -> str:
194195

195196
def __hash__(self) -> int:
196197
"""Return the hash of the function result content."""
198+
hashable_result = make_hashable(self.result)
197199
return hash((
198200
self.tag,
199201
self.id,
200-
tuple(self.result) if isinstance(self.result, list) else self.result,
202+
hashable_result,
201203
self.name,
202204
self.function_name,
203205
self.plugin_name,
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
# Copyright (c) Microsoft. All rights reserved.
2+
3+
from typing import Any
4+
5+
from pydantic import BaseModel
6+
7+
8+
def make_hashable(input: Any) -> Any:
9+
"""Recursively convert unhashable types to hashable equivalents.
10+
11+
Args:
12+
input: The input to convert to a hashable type.
13+
14+
Returns:
15+
Any: The input converted to a hashable type.
16+
"""
17+
if isinstance(input, dict):
18+
return tuple(sorted((k, make_hashable(v)) for k, v in input.items()))
19+
if isinstance(input, (list, set, tuple)):
20+
# Convert lists, sets, and tuples to tuples so they can be hashed
21+
return tuple(make_hashable(item) for item in input)
22+
if isinstance(input, BaseModel):
23+
# If obj is a Pydantic model, convert it to a dict and process
24+
return make_hashable(input.model_dump())
25+
return input # Return the input if it's already hashable

‎python/semantic_kernel/processes/process_step_builder.py‎

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -189,9 +189,18 @@ def build_step(self) -> "KernelProcessStepInfo":
189189
# Return an instance of KernelProcessStepInfo with the built state and edges.
190190
return KernelProcessStepInfo(inner_step_type=step_cls, state=state_object, output_edges=built_edges)
191191

192-
def on_function_result(self, function_name: str) -> "ProcessStepEdgeBuilder":
193-
"""Creates a new ProcessStepEdgeBuilder for the function result."""
194-
return self.on_event(f"{function_name}.OnResult")
192+
def on_function_result(self, function_name: str | Enum) -> "ProcessStepEdgeBuilder":
193+
"""Creates a new ProcessStepEdgeBuilder for the function result.
194+
195+
Args:
196+
function_name: The function name as a string or Enum.
197+
198+
Returns:
199+
ProcessStepEdgeBuilder: The ProcessStepEdgeBuilder instance.
200+
"""
201+
function_name_str: str = function_name.value if isinstance(function_name, Enum) else function_name
202+
203+
return self.on_event(f"{function_name_str}.OnResult")
195204

196205
def get_function_metadata_map(
197206
self, plugin_type, name: str | None = None, kernel: "Kernel | None" = None

‎python/tests/unit/contents/test_function_result_content.py‎

Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
from unittest.mock import Mock
55

66
import pytest
7+
from pydantic import BaseModel, ConfigDict, Field
78

89
from semantic_kernel.contents.chat_message_content import ChatMessageContent
910
from semantic_kernel.contents.function_call_content import FunctionCallContent
@@ -12,6 +13,7 @@
1213
from semantic_kernel.contents.text_content import TextContent
1314
from semantic_kernel.functions.function_result import FunctionResult
1415
from semantic_kernel.functions.kernel_function_metadata import KernelFunctionMetadata
16+
from semantic_kernel.kernel_pydantic import KernelBaseModel
1517

1618

1719
class CustomResultClass:
@@ -34,6 +36,17 @@ def __str__(self):
3436
return f"CustomObjectWithList({self.items})"
3537

3638

39+
class AccountBalanceFrozen(KernelBaseModel):
40+
# Make the model frozen so it's hashable
41+
balance: int = Field(..., alias="account_balance")
42+
model_config = ConfigDict(frozen=True)
43+
44+
45+
class AccountBalanceNonFrozen(KernelBaseModel):
46+
# This model is not frozen and thus not hashable by default
47+
balance: int = Field(..., alias="account_balance")
48+
49+
3750
def test_init():
3851
frc = FunctionResultContent(id="test", name="test-function", result="test-result", metadata={"test": "test"})
3952
assert frc.name == "test-function"
@@ -124,3 +137,83 @@ def __str__(self) -> str:
124137
frc.model_dump_json(exclude_none=True)
125138
== """{"metadata":{},"content_type":"function_result","id":"test","result":"test","name":"test-function","function_name":"function","plugin_name":"test"}""" # noqa: E501
126139
)
140+
141+
142+
def test_hash_with_frozen_account_balance():
143+
balance = AccountBalanceFrozen(account_balance=100)
144+
content = FunctionResultContent(
145+
id="test_id",
146+
result=balance,
147+
function_name="TestFunction",
148+
)
149+
_ = hash(content)
150+
assert True, "Hashing FunctionResultContent with frozen model should not raise errors."
151+
152+
153+
def test_hash_with_dict_result():
154+
balance_dict = {"account_balance": 100}
155+
content = FunctionResultContent(
156+
id="test_id",
157+
result=balance_dict,
158+
function_name="TestFunction",
159+
)
160+
_ = hash(content)
161+
assert True, "Hashing FunctionResultContent with dict result should not raise errors."
162+
163+
164+
def test_hash_with_nested_dict_result():
165+
nested_dict = {"account_balance": 100, "details": {"currency": "USD", "last_updated": "2025-01-28"}}
166+
content = FunctionResultContent(
167+
id="test_id_nested",
168+
result=nested_dict,
169+
function_name="TestFunctionNested",
170+
)
171+
_ = hash(content)
172+
assert True, "Hashing FunctionResultContent with nested dict result should not raise errors."
173+
174+
175+
def test_hash_with_list_result():
176+
balance_list = [100, 200, 300]
177+
content = FunctionResultContent(
178+
id="test_id_list",
179+
result=balance_list,
180+
function_name="TestFunctionList",
181+
)
182+
_ = hash(content)
183+
assert True, "Hashing FunctionResultContent with list result should not raise errors."
184+
185+
186+
def test_hash_with_set_result():
187+
balance_set = {100, 200, 300}
188+
content = FunctionResultContent(
189+
id="test_id_set",
190+
result=balance_set,
191+
function_name="TestFunctionSet",
192+
)
193+
_ = hash(content)
194+
assert True, "Hashing FunctionResultContent with set result should not raise errors."
195+
196+
197+
def test_hash_with_custom_object_result():
198+
class CustomObject(BaseModel):
199+
field1: str
200+
field2: int
201+
202+
custom_obj = CustomObject(field1="value1", field2=42)
203+
content = FunctionResultContent(
204+
id="test_id_custom",
205+
result=custom_obj,
206+
function_name="TestFunctionCustom",
207+
)
208+
_ = hash(content)
209+
assert True, "Hashing FunctionResultContent with custom object result should not raise errors."
210+
211+
212+
def test_unhashable_non_frozen_model_raises_type_error():
213+
balance = AccountBalanceNonFrozen(account_balance=100)
214+
content = FunctionResultContent(
215+
id="test_id_unhashable",
216+
result=balance,
217+
function_name="TestFunctionUnhashable",
218+
)
219+
_ = hash(content)

‎python/tests/unit/processes/test_process_step_builder.py‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
# Copyright (c) Microsoft. All rights reserved.
22

3+
from enum import Enum
34
from unittest.mock import MagicMock
45

56
import pytest
@@ -14,6 +15,10 @@
1415
from semantic_kernel.processes.process_step_edge_builder import ProcessStepEdgeBuilder
1516

1617

18+
class TestFunctionEnum(Enum):
19+
MY_FUNCTION = "my_function"
20+
21+
1722
class MockKernelProcessStep(KernelProcessStep):
1823
"""A mock class to use as a step type."""
1924

@@ -177,3 +182,24 @@ def test_link_to_multiple_edges():
177182

178183
# Assert
179184
assert step_builder.edges[event_id] == [edge_builder_1, edge_builder_2]
185+
186+
187+
@pytest.mark.parametrize(
188+
"function_name, expected_function_name",
189+
[
190+
("my_function", "my_function"),
191+
(TestFunctionEnum.MY_FUNCTION, TestFunctionEnum.MY_FUNCTION.value),
192+
],
193+
)
194+
def test_on_function_result(function_name, expected_function_name):
195+
# Arrange
196+
name = "test_step"
197+
step_builder = ProcessStepBuilder(name=name)
198+
199+
# Act
200+
edge_builder = step_builder.on_function_result(function_name=function_name)
201+
202+
# Assert
203+
assert isinstance(edge_builder, ProcessStepEdgeBuilder)
204+
assert edge_builder.source == step_builder
205+
assert edge_builder.event_id == f"{step_builder.event_namespace}.{expected_function_name}.OnResult"

0 commit comments

Comments
 (0)