Skip to content

Commit 2076e07

Browse files
committed
Add example test
1 parent e2e7d3b commit 2076e07

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

service/src/test/java/com/launchableinc/openai/service/ChatCompletionTest.java

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,12 @@
22

33
import com.fasterxml.jackson.annotation.JsonProperty;
44
import com.fasterxml.jackson.annotation.JsonPropertyDescription;
5+
import com.fasterxml.jackson.core.JsonProcessingException;
56
import com.fasterxml.jackson.databind.JsonNode;
7+
import com.fasterxml.jackson.databind.ObjectMapper;
68
import com.fasterxml.jackson.databind.node.ObjectNode;
79
import com.launchableinc.openai.completion.chat.*;
10+
import com.launchableinc.openai.completion.chat.ChatResponseFormat.ResponseFormat;
811
import org.junit.jupiter.api.Assumptions;
912
import org.junit.jupiter.api.BeforeAll;
1013
import org.junit.jupiter.api.Test;
@@ -77,6 +80,37 @@ void createChatCompletion() {
7780
assertEquals(5, choices.size());
7881
}
7982

83+
@Test
84+
void createChatCompletion_with_json_mode() {
85+
final List<ChatMessage> messages = new ArrayList<>();
86+
final ChatMessage systemMessage = new ChatMessage(ChatMessageRole.SYSTEM.value(),
87+
"Generate a random name and age json object. name field is a object that has first and last fields. age is a number.");
88+
messages.add(systemMessage);
89+
90+
ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest
91+
.builder()
92+
.model("gpt-3.5-turbo-1106")
93+
.messages(messages)
94+
.maxTokens(50)
95+
.logitBias(new HashMap<>())
96+
.responseFormat(ChatResponseFormat.builder().type(ResponseFormat.JSON).build())
97+
.build();
98+
99+
ChatCompletionChoice choices = service.createChatCompletion(chatCompletionRequest)
100+
.getChoices().get(0);
101+
assertTrue(isValidJson(choices.getMessage().getContent()));
102+
}
103+
104+
private boolean isValidJson(String jsonString) {
105+
ObjectMapper objectMapper = new ObjectMapper();
106+
try {
107+
objectMapper.readTree(jsonString);
108+
return true;
109+
} catch (JsonProcessingException e) {
110+
return false;
111+
}
112+
}
113+
80114
@Test
81115
void streamChatCompletion() {
82116
final List<ChatMessage> messages = new ArrayList<>();

0 commit comments

Comments
 (0)