Java: Fix chat message parsing (#5822)

### Motivation and Context

<!-- 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

<!-- 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: -->

- [ ] 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 😄
This commit is contained in:
John Oliver
2024-04-09 22:30:23 +01:00
committed by GitHub
parent 32c7e45507
commit 0afe9c5468
10 changed files with 54 additions and 12 deletions
+7 -1
View File
@@ -1,6 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
@@ -50,6 +51,10 @@
<groupId>com.github.spotbugs</groupId>
<artifactId>spotbugs-annotations</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-text</artifactId>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
@@ -72,6 +77,7 @@
<artifactId>mockito-junit-jupiter</artifactId>
<version>5.11.0</version>
</dependency>
</dependencies>
<build>
@@ -9,6 +9,7 @@ import java.util.List;
import java.util.Optional;
import java.util.function.Function;
import javax.annotation.Nullable;
import org.apache.commons.text.StringEscapeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -24,6 +25,7 @@ public class ContextVariableTypeConverter<T> {
ContextVariableTypeConverter.class);
public interface ToPromptStringFunction<T> {
String toPromptString(ContextVariableTypes types, T t);
}
@@ -389,4 +391,18 @@ public class ContextVariableTypeConverter<T> {
fromPromptString);
}
}
/**
* To be used when toPromptString is called
*
* @param value the value to escape
* @return the escaped value
*/
@Nullable
public static String escapeXmlString(@Nullable String value) {
if (value == null) {
return null;
}
return StringEscapeUtils.escapeXml11(value);
}
}
@@ -43,7 +43,7 @@ public class ChatHistoryVariableContextVariableTypeConverter extends
.stream()
.map(message -> String.format("<message role=\"%s\">%s</message>",
message.getAuthorRole(),
message.getContent()))
escapeXmlString(message.getContent())))
.collect(Collectors.joining("\n"));
return String.format("<messages>%n%s%n</messages>", messages);
@@ -41,12 +41,15 @@ public class CollectionVariableContextVariableTypeConverter extends
this(",");
}
@SuppressWarnings("NullAway")
public static ToPromptStringFunction<Collection> getString(String delimiter) {
return (types, collection) -> {
return (String) collection
String formatted = (String) collection
.stream()
.map(t -> getString(types, t))
.collect(Collectors.joining(delimiter));
return escapeXmlString(formatted);
};
}
@@ -34,7 +34,7 @@ public class PrimitiveVariableContextVariableTypeConverter<T> extends
super(
clazz,
s -> convert(s, clazz),
toPromptString,
s -> escapeXmlString(toPromptString.apply(s)),
fromPromptString);
this.fromObject = fromObject;
}
@@ -23,7 +23,7 @@ public class StringVariableContextVariableTypeConverter extends
super(
String.class,
s -> convert(s, String.class),
Object::toString,
ContextVariableTypeConverter::escapeXmlString,
s -> s);
}
}
@@ -5,6 +5,7 @@ import static com.microsoft.semantickernel.contextvariables.ContextVariableTypes
import com.microsoft.semantickernel.contextvariables.ContextVariableTypeConverter;
import com.microsoft.semantickernel.services.textcompletion.TextContent;
import javax.annotation.Nullable;
/**
* A converter for a context variable type. This class is used to convert objects to and from a
@@ -21,10 +22,18 @@ public class TextContentVariableContextVariableTypeConverter extends
super(
TextContent.class,
s -> convert(s, TextContent.class),
TextContent::getContent,
TextContentVariableContextVariableTypeConverter::escapeXmlStringValue,
x -> {
throw new UnsupportedOperationException(
"TextContentVariableContextVariableTypeConverter does not support fromPromptString");
});
}
@Nullable
public static String escapeXmlStringValue(@Nullable TextContent value) {
if (value == null) {
return null;
}
return escapeXmlString(value.getContent());
}
}
@@ -50,7 +50,7 @@ public class PromptExecutionSettings {
/**
* The default for {@link #getFrequencyPenalty()} if
* {@link Builder#withMaxTokens(doulbe) frequency_penalty} is not provided. Defaults to
* {@link Builder#withFrequencyPenalty(double)} frequency_penalty} is not provided. Defaults to
* {@code 0.0}
*/
public static final double DEFAULT_FREQUENCY_PENALTY = 0.0;
@@ -97,6 +97,7 @@ public class PromptExecutionSettings {
private final String user;
private final List<String> stopSequences;
private final Map<Integer, Integer> tokenSelectionBiases;
@Nullable
private final ResponseFormat responseFormat;
/**
@@ -114,8 +115,7 @@ public class PromptExecutionSettings {
* @param user The user to associate with the prompt execution.
* @param stopSequences The stop sequences to use for prompt execution.
* @param tokenSelectionBiases The token selection biases to use for prompt execution.
* @param responseFormat The response format to use for prompt execution @{link
* ResponseFormat}.
* @param responseFormat The response format to use for prompt execution {@link ResponseFormat}.
*/
@JsonCreator
public PromptExecutionSettings(
@@ -11,6 +11,7 @@ import com.github.jknack.handlebars.ValueResolver;
import com.microsoft.semantickernel.Kernel;
import com.microsoft.semantickernel.contextvariables.ContextVariable;
import com.microsoft.semantickernel.contextvariables.ContextVariableType;
import com.microsoft.semantickernel.contextvariables.ContextVariableTypeConverter;
import com.microsoft.semantickernel.exceptions.SKException;
import com.microsoft.semantickernel.orchestration.InvocationContext;
import com.microsoft.semantickernel.orchestration.ToolCallBehavior;
@@ -85,7 +86,8 @@ public class HandlebarsPromptTemplate implements PromptTemplate {
if ("role".equalsIgnoreCase(name)) {
return ((ChatMessageContent) context).getAuthorRole().name();
} else if ("content".equalsIgnoreCase(name)) {
return ((ChatMessageContent) context).getContent();
return ContextVariableTypeConverter
.escapeXmlString(((ChatMessageContent) context).getContent());
}
}
return UNRESOLVED;
@@ -104,7 +106,7 @@ public class HandlebarsPromptTemplate implements PromptTemplate {
"<message role=\"%s\">%s</message>",
((ChatMessageContent) context).getAuthorRole().toString()
.toLowerCase(Locale.ROOT),
content);
ContextVariableTypeConverter.escapeXmlString(content));
}
return UNRESOLVED;
}
+7 -1
View File
@@ -1,6 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.microsoft.semantic-kernel</groupId>
@@ -152,6 +153,11 @@
<artifactId>spotbugs-annotations</artifactId>
<version>4.8.3</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-text</artifactId>
<version>1.11.0</version>
</dependency>
</dependencies>
</dependencyManagement>