Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
6 changes: 5 additions & 1 deletion python/semantic_kernel/contents/chat_message_content.py
Original file line number Diff line number Diff line change
Expand Up @@ -294,11 +294,15 @@ def from_element(cls, element: Element) -> "ChatMessageContent":
def to_prompt(self) -> str:
"""Convert the ChatMessageContent to a prompt.

The encoding attribute of the content is not used here,
this always returns a string, the encoding is only relevant
for the actual text content, not for the prompt representation.

Returns:
str - The prompt from the ChatMessageContent.
"""
root = self.to_element()
return ElementTree.tostring(root, encoding=self.encoding or "unicode", short_empty_elements=False)
return ElementTree.tostring(root, encoding="unicode", short_empty_elements=False)

def to_dict(self, role_key: str = "role", content_key: str = "content") -> dict[str, Any]:
"""Serialize the ChatMessageContent to a dictionary.
Expand Down
18 changes: 18 additions & 0 deletions python/tests/unit/contents/test_chat_message_content.py
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,24 @@ def test_cmc_to_prompt():
assert prompt == '<message role="user"><text>Hello, world!</text></message>'


@pytest.mark.parametrize(
"encoding",
[
pytest.param("utf-8", id="utf8"),
pytest.param("ascii", id="ascii"),
pytest.param("latin-1", id="latin1"),
],
)
def test_cmc_to_prompt_with_encoding(encoding: str):
"""The encoding of the content should not change the type or shape of the prompt."""
message = ChatMessageContent(role=AuthorRole.USER, content="Hello, wörld!", encoding=encoding)
prompt = message.to_prompt()
assert isinstance(prompt, str)
assert not prompt.startswith("<?xml")
assert "Hello, wörld!" in prompt
assert ChatMessageContent.from_element(XML(prompt)).content == "Hello, wörld!"


def test_cmc_from_element():
element = ChatMessageContent(role=AuthorRole.USER, content="Hello, world!").to_element()
message = ChatMessageContent.from_element(element)
Expand Down
Loading