Skip to content

Commit fa68d1e

Browse files
kuntal1461ilayaperumalg
authored andcommitted
chore: improve readability and fix Sonar suggestions in OpenAiChatModelMutateTests
Signed-off-by: Kuntal Maity <[email protected]>
1 parent 3092efa commit fa68d1e

File tree

5 files changed

+73
-20
lines changed

5 files changed

+73
-20
lines changed

auto-configurations/models/spring-ai-autoconfigure-model-openai/src/test/java/org/springframework/ai/model/openai/autoconfigure/OpenAiPropertiesTests.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -377,7 +377,7 @@ public void chatOptionsTest() {
377377
"spring.ai.openai.chat.options.topP=0.56",
378378

379379
// "spring.ai.openai.chat.options.toolChoice.functionName=toolChoiceFunctionName",
380-
"spring.ai.openai.chat.options.toolChoice=" + ModelOptionsUtils.toJsonString(ToolChoiceBuilder.FUNCTION("toolChoiceFunctionName")),
380+
"spring.ai.openai.chat.options.toolChoice=" + ModelOptionsUtils.toJsonString(ToolChoiceBuilder.function("toolChoiceFunctionName")),
381381

382382
"spring.ai.openai.chat.options.tools[0].function.name=myFunction1",
383383
"spring.ai.openai.chat.options.tools[0].function.description=function description",

models/spring-ai-openai/src/main/java/org/springframework/ai/openai/api/OpenAiApi.java

Lines changed: 37 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,10 @@
1616

1717
package org.springframework.ai.openai.api;
1818

19+
import java.util.Arrays;
1920
import java.util.List;
2021
import java.util.Map;
22+
import java.util.Objects;
2123
import java.util.concurrent.atomic.AtomicBoolean;
2224
import java.util.function.Consumer;
2325
import java.util.function.Predicate;
@@ -85,6 +87,12 @@ public static Builder builder() {
8587

8688
private static final Predicate<String> SSE_DONE_PREDICATE = "[DONE]"::equals;
8789

90+
private static final String REQUEST_BODY_NULL_MESSAGE = "The request body can not be null.";
91+
92+
private static final String STREAM_FALSE_MESSAGE = "Request must set the stream property to false.";
93+
94+
private static final String ADDITIONAL_HEADERS_NULL_MESSAGE = "The additional HTTP headers can not be null.";
95+
8896
// Store config fields for mutate/copy
8997
private final String baseUrl;
9098

@@ -183,9 +191,9 @@ public ResponseEntity<ChatCompletion> chatCompletionEntity(ChatCompletionRequest
183191
public ResponseEntity<ChatCompletion> chatCompletionEntity(ChatCompletionRequest chatRequest,
184192
MultiValueMap<String, String> additionalHttpHeader) {
185193

186-
Assert.notNull(chatRequest, "The request body can not be null.");
187-
Assert.isTrue(!chatRequest.stream(), "Request must set the stream property to false.");
188-
Assert.notNull(additionalHttpHeader, "The additional HTTP headers can not be null.");
194+
Assert.notNull(chatRequest, REQUEST_BODY_NULL_MESSAGE);
195+
Assert.isTrue(!chatRequest.stream(), STREAM_FALSE_MESSAGE);
196+
Assert.notNull(additionalHttpHeader, ADDITIONAL_HEADERS_NULL_MESSAGE);
189197

190198
// @formatter:off
191199
return this.restClient.post()
@@ -221,7 +229,7 @@ public Flux<ChatCompletionChunk> chatCompletionStream(ChatCompletionRequest chat
221229
public Flux<ChatCompletionChunk> chatCompletionStream(ChatCompletionRequest chatRequest,
222230
MultiValueMap<String, String> additionalHttpHeader) {
223231

224-
Assert.notNull(chatRequest, "The request body can not be null.");
232+
Assert.notNull(chatRequest, REQUEST_BODY_NULL_MESSAGE);
225233
Assert.isTrue(chatRequest.stream(), "Request must set the stream property to true.");
226234

227235
AtomicBoolean isInsideTool = new AtomicBoolean(false);
@@ -284,7 +292,7 @@ public Flux<ChatCompletionChunk> chatCompletionStream(ChatCompletionRequest chat
284292
*/
285293
public <T> ResponseEntity<EmbeddingList<Embedding>> embeddings(EmbeddingRequest<T> embeddingRequest) {
286294

287-
Assert.notNull(embeddingRequest, "The request body can not be null.");
295+
Assert.notNull(embeddingRequest, REQUEST_BODY_NULL_MESSAGE);
288296

289297
// Input text to embed, encoded as a string or array of tokens. To embed multiple
290298
// inputs in a single
@@ -296,7 +304,7 @@ public <T> ResponseEntity<EmbeddingList<Embedding>> embeddings(EmbeddingRequest<
296304
// The input must not exceed the max input tokens for the model (8192 tokens for
297305
// text-embedding-ada-002), cannot
298306
// be an empty string, and any array must be 2048 dimensions or less.
299-
if (embeddingRequest.input() instanceof List list) {
307+
if (embeddingRequest.input() instanceof List<?> list) {
300308
Assert.isTrue(!CollectionUtils.isEmpty(list), "The input list can not be empty.");
301309
Assert.isTrue(list.size() <= 2048, "The list must be 2048 dimensions or less");
302310
Assert.isTrue(
@@ -1218,7 +1226,7 @@ public static class ToolChoiceBuilder {
12181226
/**
12191227
* Specifying a particular function forces the model to call that function.
12201228
*/
1221-
public static Object FUNCTION(String functionName) {
1229+
public static Object function(String functionName) {
12221230
return Map.of("type", "function", "function", Map.of("name", functionName));
12231231
}
12241232
}
@@ -1877,7 +1885,9 @@ public record ChunkChoice(// @formatter:off
18771885
@JsonIgnoreProperties(ignoreUnknown = true)
18781886
public record Embedding(// @formatter:off
18791887
@JsonProperty("index") Integer index,
1880-
@JsonProperty("embedding") @JsonDeserialize(using = OpenAiEmbeddingDeserializer.class) float[] embedding,
1888+
@JsonProperty("embedding")
1889+
@JsonDeserialize(using = OpenAiEmbeddingDeserializer.class)
1890+
float[] embedding,
18811891
@JsonProperty("object") String object) { // @formatter:on
18821892

18831893
/**
@@ -1891,6 +1901,25 @@ public Embedding(Integer index, float[] embedding) {
18911901
this(index, embedding, "embedding");
18921902
}
18931903

1904+
@Override
1905+
public boolean equals(Object o) {
1906+
if (this == o) {
1907+
return true;
1908+
}
1909+
if (!(o instanceof Embedding other)) {
1910+
return false;
1911+
}
1912+
return Objects.equals(this.index, other.index) && Arrays.equals(this.embedding, other.embedding)
1913+
&& Objects.equals(this.object, other.object);
1914+
}
1915+
1916+
@Override
1917+
public int hashCode() {
1918+
int result = Objects.hash(this.index, this.object);
1919+
result = 31 * result + Arrays.hashCode(this.embedding);
1920+
return result;
1921+
}
1922+
18941923
}
18951924

18961925
/**

models/spring-ai-openai/src/main/java/org/springframework/ai/openai/api/OpenAiFileApi.java

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,9 @@
1616

1717
package org.springframework.ai.openai.api;
1818

19+
import java.util.Arrays;
1920
import java.util.List;
21+
import java.util.Objects;
2022
import java.util.function.Consumer;
2123

2224
import com.fasterxml.jackson.annotation.JsonInclude;
@@ -201,6 +203,32 @@ public static Builder builder() {
201203
return new Builder();
202204
}
203205

206+
@Override
207+
public boolean equals(Object o) {
208+
if (this == o) {
209+
return true;
210+
}
211+
if (!(o instanceof UploadFileRequest that)) {
212+
return false;
213+
}
214+
return Arrays.equals(this.file, that.file) && Objects.equals(this.fileName, that.fileName)
215+
&& Objects.equals(this.purpose, that.purpose);
216+
}
217+
218+
@Override
219+
public int hashCode() {
220+
int result = Arrays.hashCode(this.file);
221+
result = 31 * result + Objects.hashCode(this.fileName);
222+
result = 31 * result + Objects.hashCode(this.purpose);
223+
return result;
224+
}
225+
226+
@Override
227+
public String toString() {
228+
return "UploadFileRequest{file=" + Arrays.toString(this.file) + ", fileName="
229+
+ Objects.toString(this.fileName) + ", purpose=" + Objects.toString(this.purpose) + "}";
230+
}
231+
204232
public static final class Builder {
205233

206234
private byte[] file;

models/spring-ai-openai/src/test/java/org/springframework/ai/openai/api/OpenAiApiIT.java

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@
4646
* @author Alexandros Pappas
4747
*/
4848
@EnabledIfEnvironmentVariable(named = "OPENAI_API_KEY", matches = ".+")
49-
public class OpenAiApiIT {
49+
class OpenAiApiIT {
5050

5151
OpenAiApi openAiApi = OpenAiApi.builder().apiKey(System.getenv("OPENAI_API_KEY")).build();
5252

@@ -117,7 +117,7 @@ void inputAudio() throws IOException {
117117
assertThat(response.getBody()).isNotNull();
118118

119119
assertThat(response.getBody().usage().promptTokensDetails().audioTokens()).isGreaterThan(0);
120-
assertThat(response.getBody().usage().completionTokenDetails().audioTokens()).isEqualTo(0);
120+
assertThat(response.getBody().usage().completionTokenDetails().audioTokens()).isZero();
121121

122122
assertThat(response.getBody().choices().get(0).message().content()).containsIgnoringCase("hobbits");
123123
}
@@ -135,7 +135,7 @@ void outputAudio() {
135135
assertThat(response).isNotNull();
136136
assertThat(response.getBody()).isNotNull();
137137

138-
assertThat(response.getBody().usage().promptTokensDetails().audioTokens()).isEqualTo(0);
138+
assertThat(response.getBody().usage().promptTokensDetails().audioTokens()).isZero();
139139
assertThat(response.getBody().usage().completionTokenDetails().audioTokens()).isGreaterThan(0);
140140

141141
assertThat(response.getBody().choices().get(0).message().audioOutput().data()).isNotNull();
@@ -153,8 +153,9 @@ void streamOutputAudio() {
153153
ChatCompletionRequest chatCompletionRequest = new ChatCompletionRequest(List.of(chatCompletionMessage),
154154
OpenAiApi.ChatModel.GPT_4_O_AUDIO_PREVIEW.getValue(), audioParameters, true);
155155

156-
assertThatThrownBy(() -> this.openAiApi.chatCompletionStream(chatCompletionRequest).collectList().block())
157-
.isInstanceOf(RuntimeException.class)
156+
Flux<ChatCompletionChunk> response = this.openAiApi.chatCompletionStream(chatCompletionRequest);
157+
158+
assertThatThrownBy(response::blockLast).isInstanceOf(RuntimeException.class)
158159
.hasMessageContaining("400 Bad Request from POST https://api.openai.com/v1/chat/completions");
159160
}
160161

models/spring-ai-openai/src/test/java/org/springframework/ai/openai/api/OpenAiChatModelMutateTests.java

Lines changed: 1 addition & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,6 @@
1818

1919
import org.junit.jupiter.api.Test;
2020

21-
import org.springframework.ai.chat.client.ChatClient;
2221
import org.springframework.ai.openai.OpenAiChatModel;
2322
import org.springframework.ai.openai.OpenAiChatOptions;
2423
import org.springframework.util.LinkedMultiValueMap;
@@ -52,8 +51,6 @@ void testMutateCreatesDistinctClientsWithDifferentEndpointsAndModels() {
5251
.openAiApi(gpt4Api)
5352
.defaultOptions(OpenAiChatOptions.builder().model("gpt-4").temperature(0.7).build())
5453
.build();
55-
ChatClient gpt4Client = ChatClient.builder(gpt4Model).build();
56-
5754
// Mutate for Llama
5855
OpenAiApi llamaApi = this.baseApi.mutate()
5956
.baseUrl("https://your-custom-endpoint.com")
@@ -63,8 +60,6 @@ void testMutateCreatesDistinctClientsWithDifferentEndpointsAndModels() {
6360
.openAiApi(llamaApi)
6461
.defaultOptions(OpenAiChatOptions.builder().model("llama-70b").temperature(0.5).build())
6562
.build();
66-
ChatClient llamaClient = ChatClient.builder(llamaModel).build();
67-
6863
// Assert endpoints and models are different
6964
assertThat(gpt4Model).isNotSameAs(llamaModel);
7065
assertThat(gpt4Api).isNotSameAs(llamaApi);
@@ -78,7 +73,7 @@ void testMutateCreatesDistinctClientsWithDifferentEndpointsAndModels() {
7873
void testCloneCreatesDeepCopy() {
7974
OpenAiChatModel clone = this.baseModel.clone();
8075
assertThat(clone).isNotSameAs(this.baseModel);
81-
assertThat(clone.toString()).isEqualTo(this.baseModel.toString());
76+
assertThat(clone).hasToString(this.baseModel.toString());
8277
}
8378

8479
@Test

0 commit comments

Comments
 (0)