diff --git a/python/semantic_kernel/prompt_template/utils/handlebars_system_helpers.py b/python/semantic_kernel/prompt_template/utils/handlebars_system_helpers.py index ea60447f2cb9..74734b280a80 100644 --- a/python/semantic_kernel/prompt_template/utils/handlebars_system_helpers.py +++ b/python/semantic_kernel/prompt_template/utils/handlebars_system_helpers.py @@ -10,12 +10,15 @@ logger: logging.Logger = logging.getLogger(__name__) -def _messages(this, options, *args, **kwargs): +def _messages(this, *args, **kwargs): from semantic_kernel.contents.chat_history import ChatHistory - if not isinstance(this.context["chat_history"], ChatHistory): + # Use the argument passed to the helper, e.g. {{messages my_history}}. + # Fall back to the "chat_history" variable when no argument is given. + chat_history = args[0] if args else this.context.get("chat_history") + if not isinstance(chat_history, ChatHistory): return "" - return this.context["chat_history"].to_prompt() + return chat_history.to_prompt() def _message_to_prompt(this, *args, **kwargs): diff --git a/python/tests/unit/prompt_template/test_handlebars_prompt_template.py b/python/tests/unit/prompt_template/test_handlebars_prompt_template.py index 6efea53f50c7..fb255676fc35 100644 --- a/python/tests/unit/prompt_template/test_handlebars_prompt_template.py +++ b/python/tests/unit/prompt_template/test_handlebars_prompt_template.py @@ -479,3 +479,37 @@ async def test_safe_types_are_allowed(): assert "42" in result assert "true" in result + + +async def test_helpers_chat_history_messages_uses_argument(kernel: Kernel): + template = """{{messages history}}""" + target = create_handlebars_prompt_template(template, allow_dangerously_set_content=True) + chat_history = ChatHistory() + chat_history.add_user_message("User message") + rendered = await target.render(kernel, KernelArguments(history=chat_history)) + assert ( + rendered.strip() == """User message""" + ) + + +async def test_helpers_chat_history_messages_prefers_argument_over_chat_history_variable(kernel: Kernel): + template = """{{messages other}}""" + target = create_handlebars_prompt_template(template, allow_dangerously_set_content=True) + wrong = ChatHistory() + wrong.add_user_message("WRONG") + right = ChatHistory() + right.add_user_message("RIGHT") + rendered = await target.render(kernel, KernelArguments(chat_history=wrong, other=right)) + assert "RIGHT" in rendered + assert "WRONG" not in rendered + + +async def test_helpers_chat_history_messages_without_argument_uses_chat_history_variable(kernel: Kernel): + template = """{{messages}}""" + target = create_handlebars_prompt_template(template, allow_dangerously_set_content=True) + chat_history = ChatHistory() + chat_history.add_user_message("User message") + rendered = await target.render(kernel, KernelArguments(chat_history=chat_history)) + assert ( + rendered.strip() == """User message""" + )