diff --git a/python/packages/core/agent_framework/_types.py b/python/packages/core/agent_framework/_types.py index 990c55c4ae..360ab58bd4 100644 --- a/python/packages/core/agent_framework/_types.py +++ b/python/packages/core/agent_framework/_types.py @@ -2009,6 +2009,13 @@ def prepend_instructions_to_messages( if isinstance(instructions, str): instructions = [instructions] + # An empty instruction list (or all-empty strings) adds nothing; without + # this a caller that passes an unset options default of "" gets a + # contentless system message injected ahead of the real conversation. + instructions = [part for part in instructions if part.strip()] + if not instructions: + return messages + # Skip instructions that are already present as the leading messages with the # same role and text. This prevents duplicate system messages when # instructions are injected by multiple layers (e.g. Agent + chat client). diff --git a/python/packages/core/tests/test_types.py b/python/packages/core/tests/test_types.py new file mode 100644 index 0000000000..67e7e362e5 --- /dev/null +++ b/python/packages/core/tests/test_types.py @@ -0,0 +1,21 @@ + + +class TestPrependInstructionsEmpty: + def test_empty_string_instructions_add_no_message(self) -> None: + """An unset "" instruction must not inject a contentless system message.""" + from agent_framework import Message, prepend_instructions_to_messages + + messages = [Message(role="user", contents=["hi"])] + out = prepend_instructions_to_messages(messages, "") + assert [(m.role, [getattr(c, "text", c) for c in m.contents]) for m in out] == [("user", ["hi"])] + + def test_whitespace_only_instructions_add_no_message(self) -> None: + from agent_framework import prepend_instructions_to_messages + + assert prepend_instructions_to_messages([], ["", " "]) == [] + + def test_real_instructions_still_prepend_verbatim(self) -> None: + from agent_framework import Message, prepend_instructions_to_messages + + out = prepend_instructions_to_messages([], [" real "]) + assert [(m.role, [getattr(c, "text", c) for c in m.contents]) for m in out] == [("system", [" real "])]