Skip to content

Commit b427208

Browse files
Python: FunctionResultContent hash fix to handle lists/sets (#9978)
### Motivation and Context Currently, the hash function in `FunctionResultContent` does not properly handle types of list or set. Adding the proper handling to turn these into a tuple, and then the hash function works properly. <!-- 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: - Makes sure the FunctionResultContent `__hash__` method can properly handle mutable types like lists or sets - Adds tests to ensure the new behavior works as expected - Ensures the create message content method can handle lists or sets when generating the content and the model can only accept a string. - Fixes #9977 <!-- 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 😄 --------- Co-authored-by: Eduard van Valkenburg <[email protected]>
1 parent 62a50f3 commit b427208

5 files changed

Lines changed: 71 additions & 6 deletions

File tree

‎python/semantic_kernel/agents/open_ai/assistant_content_generation.py‎

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -87,17 +87,36 @@ def get_message_contents(message: "ChatMessageContent") -> list[dict[str, Any]]:
8787
for content in message.items:
8888
match content:
8989
case TextContent():
90-
contents.append({"type": "text", "text": content.text})
90+
# Make sure text is a string
91+
final_text = content.text
92+
if not isinstance(final_text, str):
93+
if isinstance(final_text, (list, tuple)):
94+
final_text = " ".join(map(str, final_text))
95+
else:
96+
final_text = str(final_text)
97+
98+
contents.append({"type": "text", "text": final_text})
99+
91100
case ImageContent():
92101
if content.uri:
93102
contents.append(content.to_dict())
103+
94104
case FileReferenceContent():
95105
contents.append({
96106
"type": "image_file",
97107
"image_file": {"file_id": content.file_id},
98108
})
109+
99110
case FunctionResultContent():
100-
contents.append({"type": "text", "text": content.result})
111+
final_result = content.result
112+
match final_result:
113+
case str():
114+
contents.append({"type": "text", "text": final_result})
115+
case list() | tuple():
116+
contents.append({"type": "text", "text": " ".join(map(str, final_result))})
117+
case _:
118+
contents.append({"type": "text", "text": str(final_result)})
119+
101120
return contents
102121

103122

‎python/semantic_kernel/contents/function_result_content.py‎

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
if TYPE_CHECKING:
1818
from semantic_kernel.contents.chat_message_content import ChatMessageContent
1919
from semantic_kernel.contents.function_call_content import FunctionCallContent
20+
from semantic_kernel.contents.streaming_chat_message_content import StreamingChatMessageContent
2021
from semantic_kernel.functions.function_result import FunctionResult
2122

2223
TAG_CONTENT_MAP = {
@@ -157,6 +158,12 @@ def to_chat_message_content(self) -> "ChatMessageContent":
157158

158159
return ChatMessageContent(role=AuthorRole.TOOL, items=[self])
159160

161+
def to_streaming_chat_message_content(self) -> "StreamingChatMessageContent":
162+
"""Convert the instance to a StreamingChatMessageContent."""
163+
from semantic_kernel.contents.streaming_chat_message_content import StreamingChatMessageContent
164+
165+
return StreamingChatMessageContent(role=AuthorRole.TOOL, choice_index=0, items=[self])
166+
160167
def to_dict(self) -> dict[str, str]:
161168
"""Convert the instance to a dictionary."""
162169
return {
@@ -187,4 +194,12 @@ def serialize_result(self, value: Any) -> str:
187194

188195
def __hash__(self) -> int:
189196
"""Return the hash of the function result content."""
190-
return hash((self.tag, self.id, self.result, self.name, self.function_name, self.plugin_name, self.encoding))
197+
return hash((
198+
self.tag,
199+
self.id,
200+
tuple(self.result) if isinstance(self.result, list) else self.result,
201+
self.name,
202+
self.function_name,
203+
self.plugin_name,
204+
self.encoding,
205+
))

‎python/semantic_kernel/functions/kernel_function_from_prompt.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
from html import unescape
77
from typing import TYPE_CHECKING, Any
88

9-
import yaml
9+
import yaml # type: ignore
1010
from pydantic import Field, ValidationError, model_validator
1111

1212
from semantic_kernel.connectors.ai.chat_completion_client_base import ChatCompletionClientBase

‎python/tests/unit/agents/test_open_ai_assistant_base.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1487,6 +1487,8 @@ def test_get_message_contents(azure_openai_assistant_agent: AzureAssistantAgent,
14871487
ImageContent(role=AuthorRole.ASSISTANT, content="test message", uri="http://image.url"),
14881488
TextContent(role=AuthorRole.ASSISTANT, text="test message"),
14891489
FileReferenceContent(role=AuthorRole.ASSISTANT, file_id="test_file_id"),
1490+
TextContent(role=AuthorRole.USER, text="test message"),
1491+
FunctionResultContent(role=AuthorRole.ASSISTANT, result=["test result"], id="test_id"),
14901492
]
14911493

14921494
result = get_message_contents(message)

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

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

33

4-
from typing import Any
54
from unittest.mock import Mock
65

76
import pytest
@@ -15,6 +14,26 @@
1514
from semantic_kernel.functions.kernel_function_metadata import KernelFunctionMetadata
1615

1716

17+
class CustomResultClass:
18+
"""Custom class for testing."""
19+
20+
def __init__(self, result):
21+
self.result = result
22+
23+
def __str__(self) -> str:
24+
return self.result
25+
26+
27+
class CustomObjectWithList:
28+
"""Custom class for testing."""
29+
30+
def __init__(self, items):
31+
self.items = items
32+
33+
def __str__(self):
34+
return f"CustomObjectWithList({self.items})"
35+
36+
1837
def test_init():
1938
frc = FunctionResultContent(id="test", name="test-function", result="test-result", metadata={"test": "test"})
2039
assert frc.name == "test-function"
@@ -50,6 +69,11 @@ def test_init_from_names():
5069
ChatMessageContent(role="user", content="Hello world!"),
5170
ChatMessageContent(role="user", items=[ImageContent(uri="https://example.com")]),
5271
ChatMessageContent(role="user", items=[FunctionResultContent(id="test", name="test", result="Hello world!")]),
72+
[1, 2, 3],
73+
[{"key": "value"}, {"another": "item"}],
74+
{"a", "b"},
75+
CustomResultClass("test"),
76+
CustomObjectWithList(["one", "two", "three"]),
5377
],
5478
ids=[
5579
"str",
@@ -60,9 +84,14 @@ def test_init_from_names():
6084
"ChatMessageContent",
6185
"ChatMessageContent-ImageContent",
6286
"ChatMessageContent-FunctionResultContent",
87+
"list",
88+
"list_of_dicts",
89+
"set",
90+
"CustomResultClass",
91+
"CustomObjectWithList",
6392
],
6493
)
65-
def test_from_fcc_and_result(result: Any):
94+
def test_from_fcc_and_result(result: any):
6695
fcc = FunctionCallContent(
6796
id="test", name="test-function", arguments='{"input": "world"}', metadata={"test": "test"}
6897
)

0 commit comments

Comments
 (0)