From 018aae5d44a740278decf863fb44b2462a1081c8 Mon Sep 17 00:00:00 2001 From: John Oliver <1615532+johnoliver@users.noreply.github.com> Date: Tue, 19 Mar 2024 19:32:15 +0000 Subject: [PATCH] Java: Allow creating empty ChatHistory (#5525) ### Motivation and Context ### Description ### Contribution Checklist - [ ] The code builds clean without any errors or warnings - [ ] 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 - [ ] All unit tests pass, and I have added new tests where possible - [ ] I didn't break anyone :smile: --- .../services/chatcompletion/ChatHistory.java | 27 ++++++++++++++----- 1 file changed, 20 insertions(+), 7 deletions(-) diff --git a/java/semantickernel-api/src/main/java/com/microsoft/semantickernel/services/chatcompletion/ChatHistory.java b/java/semantickernel-api/src/main/java/com/microsoft/semantickernel/services/chatcompletion/ChatHistory.java index 5ac4bc91ee..62b05b4b5c 100644 --- a/java/semantickernel-api/src/main/java/com/microsoft/semantickernel/services/chatcompletion/ChatHistory.java +++ b/java/semantickernel-api/src/main/java/com/microsoft/semantickernel/services/chatcompletion/ChatHistory.java @@ -10,6 +10,7 @@ import java.util.List; import java.util.Optional; import java.util.Spliterator; import java.util.function.Consumer; +import javax.annotation.Nullable; /** * Provides a history of messages between the User, Assistant and System @@ -25,7 +26,17 @@ public class ChatHistory implements Iterable> { * chat history */ public ChatHistory() { - this(DEFAULT_CHAT_SYSTEM_PROMPT); + this(true); + } + + /** + * Constructor that can add the default system instructions to the chat history. + * + * @param addDefaultSystemPrompt If true, the default system prompt will be added to the chat, + * otherwise empty + */ + public ChatHistory(boolean addDefaultSystemPrompt) { + this(addDefaultSystemPrompt ? DEFAULT_CHAT_SYSTEM_PROMPT : null); } /** @@ -33,13 +44,15 @@ public class ChatHistory implements Iterable> { * * @param instructions The instructions to add to the chat history */ - public ChatHistory(String instructions) { + public ChatHistory(@Nullable String instructions) { this.chatMessageContents = new ArrayList<>(); - this.chatMessageContents.add( - new ChatMessageContent<>( - AuthorRole.ASSISTANT, - instructions == null || instructions.isEmpty() ? DEFAULT_CHAT_SYSTEM_PROMPT - : instructions)); + if (instructions != null) { + + this.chatMessageContents.add( + new ChatMessageContent<>( + AuthorRole.SYSTEM, + instructions)); + } } /**